babylon.no-module.max.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @ignore */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @ignore */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @ignore */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @ignore */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @ignore */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. var Vector2 = /** @class */ (function () {
  2169. /**
  2170. * Creates a new Vector2 from the given x and y coordinates.
  2171. */
  2172. function Vector2(x, y) {
  2173. this.x = x;
  2174. this.y = y;
  2175. }
  2176. /**
  2177. * Returns a string with the Vector2 coordinates.
  2178. */
  2179. Vector2.prototype.toString = function () {
  2180. return "{X: " + this.x + " Y:" + this.y + "}";
  2181. };
  2182. /**
  2183. * Returns the string "Vector2"
  2184. */
  2185. Vector2.prototype.getClassName = function () {
  2186. return "Vector2";
  2187. };
  2188. /**
  2189. * Returns the Vector2 hash code as a number.
  2190. */
  2191. Vector2.prototype.getHashCode = function () {
  2192. var hash = this.x || 0;
  2193. hash = (hash * 397) ^ (this.y || 0);
  2194. return hash;
  2195. };
  2196. // Operators
  2197. /**
  2198. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2199. * Returns the Vector2.
  2200. */
  2201. Vector2.prototype.toArray = function (array, index) {
  2202. if (index === void 0) { index = 0; }
  2203. array[index] = this.x;
  2204. array[index + 1] = this.y;
  2205. return this;
  2206. };
  2207. /**
  2208. * Returns a new array with 2 elements : the Vector2 coordinates.
  2209. */
  2210. Vector2.prototype.asArray = function () {
  2211. var result = new Array();
  2212. this.toArray(result, 0);
  2213. return result;
  2214. };
  2215. /**
  2216. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2217. * Returns the updated Vector2.
  2218. */
  2219. Vector2.prototype.copyFrom = function (source) {
  2220. this.x = source.x;
  2221. this.y = source.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Sets the Vector2 coordinates with the given floats.
  2226. * Returns the updated Vector2.
  2227. */
  2228. Vector2.prototype.copyFromFloats = function (x, y) {
  2229. this.x = x;
  2230. this.y = y;
  2231. return this;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given floats.
  2235. * Returns the updated Vector2.
  2236. */
  2237. Vector2.prototype.set = function (x, y) {
  2238. return this.copyFromFloats(x, y);
  2239. };
  2240. /**
  2241. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2242. */
  2243. Vector2.prototype.add = function (otherVector) {
  2244. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2245. };
  2246. /**
  2247. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2248. * Returns the Vector2.
  2249. */
  2250. Vector2.prototype.addToRef = function (otherVector, result) {
  2251. result.x = this.x + otherVector.x;
  2252. result.y = this.y + otherVector.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2257. * Returns the updated Vector2.
  2258. */
  2259. Vector2.prototype.addInPlace = function (otherVector) {
  2260. this.x += otherVector.x;
  2261. this.y += otherVector.y;
  2262. return this;
  2263. };
  2264. /**
  2265. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2266. */
  2267. Vector2.prototype.addVector3 = function (otherVector) {
  2268. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2269. };
  2270. /**
  2271. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2272. */
  2273. Vector2.prototype.subtract = function (otherVector) {
  2274. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2275. };
  2276. /**
  2277. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2278. * Returns the Vector2.
  2279. */
  2280. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2281. result.x = this.x - otherVector.x;
  2282. result.y = this.y - otherVector.y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.subtractInPlace = function (otherVector) {
  2290. this.x -= otherVector.x;
  2291. this.y -= otherVector.y;
  2292. return this;
  2293. };
  2294. /**
  2295. * Multiplies in place the current Vector2 coordinates by the given ones.
  2296. * Returns the updated Vector2.
  2297. */
  2298. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2299. this.x *= otherVector.x;
  2300. this.y *= otherVector.y;
  2301. return this;
  2302. };
  2303. /**
  2304. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2305. */
  2306. Vector2.prototype.multiply = function (otherVector) {
  2307. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2308. };
  2309. /**
  2310. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2311. * Returns the Vector2.
  2312. */
  2313. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2314. result.x = this.x * otherVector.x;
  2315. result.y = this.y * otherVector.y;
  2316. return this;
  2317. };
  2318. /**
  2319. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2320. */
  2321. Vector2.prototype.multiplyByFloats = function (x, y) {
  2322. return new Vector2(this.x * x, this.y * y);
  2323. };
  2324. /**
  2325. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2326. */
  2327. Vector2.prototype.divide = function (otherVector) {
  2328. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2332. * Returns the Vector2.
  2333. */
  2334. Vector2.prototype.divideToRef = function (otherVector, result) {
  2335. result.x = this.x / otherVector.x;
  2336. result.y = this.y / otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Divides the current Vector3 coordinates by the given ones.
  2341. * Returns the updated Vector3.
  2342. */
  2343. Vector2.prototype.divideInPlace = function (otherVector) {
  2344. return this.divideToRef(otherVector, this);
  2345. };
  2346. /**
  2347. * Returns a new Vector2 with current Vector2 negated coordinates.
  2348. */
  2349. Vector2.prototype.negate = function () {
  2350. return new Vector2(-this.x, -this.y);
  2351. };
  2352. /**
  2353. * Multiply the Vector2 coordinates by scale.
  2354. * Returns the updated Vector2.
  2355. */
  2356. Vector2.prototype.scaleInPlace = function (scale) {
  2357. this.x *= scale;
  2358. this.y *= scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2363. */
  2364. Vector2.prototype.scale = function (scale) {
  2365. var result = new Vector2(0, 0);
  2366. this.scaleToRef(scale, result);
  2367. return result;
  2368. };
  2369. /**
  2370. * Scale the current Vector2 values by a factor to a given Vector2
  2371. * @param scale defines the scale factor
  2372. * @param result defines the Vector2 object where to store the result
  2373. * @returns the unmodified current Vector2
  2374. */
  2375. Vector2.prototype.scaleToRef = function (scale, result) {
  2376. result.x = this.x * scale;
  2377. result.y = this.y * scale;
  2378. return this;
  2379. };
  2380. /**
  2381. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2382. * @param scale defines the scale factor
  2383. * @param result defines the Vector2 object where to store the result
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2387. result.x += this.x * scale;
  2388. result.y += this.y * scale;
  2389. return this;
  2390. };
  2391. /**
  2392. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2393. */
  2394. Vector2.prototype.equals = function (otherVector) {
  2395. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2396. };
  2397. /**
  2398. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2399. */
  2400. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2401. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2402. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2403. };
  2404. // Properties
  2405. /**
  2406. * Returns the vector length (float).
  2407. */
  2408. Vector2.prototype.length = function () {
  2409. return Math.sqrt(this.x * this.x + this.y * this.y);
  2410. };
  2411. /**
  2412. * Returns the vector squared length (float);
  2413. */
  2414. Vector2.prototype.lengthSquared = function () {
  2415. return (this.x * this.x + this.y * this.y);
  2416. };
  2417. // Methods
  2418. /**
  2419. * Normalize the vector.
  2420. * Returns the updated Vector2.
  2421. */
  2422. Vector2.prototype.normalize = function () {
  2423. var len = this.length();
  2424. if (len === 0)
  2425. return this;
  2426. var num = 1.0 / len;
  2427. this.x *= num;
  2428. this.y *= num;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 copied from the Vector2.
  2433. */
  2434. Vector2.prototype.clone = function () {
  2435. return new Vector2(this.x, this.y);
  2436. };
  2437. // Statics
  2438. /**
  2439. * Returns a new Vector2(0, 0)
  2440. */
  2441. Vector2.Zero = function () {
  2442. return new Vector2(0, 0);
  2443. };
  2444. /**
  2445. * Returns a new Vector2(1, 1)
  2446. */
  2447. Vector2.One = function () {
  2448. return new Vector2(1, 1);
  2449. };
  2450. /**
  2451. * Returns a new Vector2 set from the given index element of the given array.
  2452. */
  2453. Vector2.FromArray = function (array, offset) {
  2454. if (offset === void 0) { offset = 0; }
  2455. return new Vector2(array[offset], array[offset + 1]);
  2456. };
  2457. /**
  2458. * Sets "result" from the given index element of the given array.
  2459. */
  2460. Vector2.FromArrayToRef = function (array, offset, result) {
  2461. result.x = array[offset];
  2462. result.y = array[offset + 1];
  2463. };
  2464. /**
  2465. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2466. */
  2467. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2468. var squared = amount * amount;
  2469. var cubed = amount * squared;
  2470. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2471. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2472. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2473. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2474. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2475. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2476. return new Vector2(x, y);
  2477. };
  2478. /**
  2479. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2480. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2481. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2482. */
  2483. Vector2.Clamp = function (value, min, max) {
  2484. var x = value.x;
  2485. x = (x > max.x) ? max.x : x;
  2486. x = (x < min.x) ? min.x : x;
  2487. var y = value.y;
  2488. y = (y > max.y) ? max.y : y;
  2489. y = (y < min.y) ? min.y : y;
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2494. */
  2495. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2496. var squared = amount * amount;
  2497. var cubed = amount * squared;
  2498. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2499. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2500. var part3 = (cubed - (2.0 * squared)) + amount;
  2501. var part4 = cubed - squared;
  2502. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2503. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2504. return new Vector2(x, y);
  2505. };
  2506. /**
  2507. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2508. */
  2509. Vector2.Lerp = function (start, end, amount) {
  2510. var x = start.x + ((end.x - start.x) * amount);
  2511. var y = start.y + ((end.y - start.y) * amount);
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns the dot product (float) of the vector "left" and the vector "right".
  2516. */
  2517. Vector2.Dot = function (left, right) {
  2518. return left.x * right.x + left.y * right.y;
  2519. };
  2520. /**
  2521. * Returns a new Vector2 equal to the normalized given vector.
  2522. */
  2523. Vector2.Normalize = function (vector) {
  2524. var newVector = vector.clone();
  2525. newVector.normalize();
  2526. return newVector;
  2527. };
  2528. /**
  2529. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2530. */
  2531. Vector2.Minimize = function (left, right) {
  2532. var x = (left.x < right.x) ? left.x : right.x;
  2533. var y = (left.y < right.y) ? left.y : right.y;
  2534. return new Vector2(x, y);
  2535. };
  2536. /**
  2537. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2538. */
  2539. Vector2.Maximize = function (left, right) {
  2540. var x = (left.x > right.x) ? left.x : right.x;
  2541. var y = (left.y > right.y) ? left.y : right.y;
  2542. return new Vector2(x, y);
  2543. };
  2544. /**
  2545. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2546. */
  2547. Vector2.Transform = function (vector, transformation) {
  2548. var r = Vector2.Zero();
  2549. Vector2.TransformToRef(vector, transformation, r);
  2550. return r;
  2551. };
  2552. /**
  2553. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2554. */
  2555. Vector2.TransformToRef = function (vector, transformation, result) {
  2556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2558. result.x = x;
  2559. result.y = y;
  2560. };
  2561. /**
  2562. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2563. */
  2564. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2565. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2566. var sign = a < 0 ? -1 : 1;
  2567. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2568. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2569. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2570. };
  2571. /**
  2572. * Returns the distance (float) between the vectors "value1" and "value2".
  2573. */
  2574. Vector2.Distance = function (value1, value2) {
  2575. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2576. };
  2577. /**
  2578. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2579. */
  2580. Vector2.DistanceSquared = function (value1, value2) {
  2581. var x = value1.x - value2.x;
  2582. var y = value1.y - value2.y;
  2583. return (x * x) + (y * y);
  2584. };
  2585. /**
  2586. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2587. */
  2588. Vector2.Center = function (value1, value2) {
  2589. var center = value1.add(value2);
  2590. center.scaleInPlace(0.5);
  2591. return center;
  2592. };
  2593. /**
  2594. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2595. */
  2596. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2597. var l2 = Vector2.DistanceSquared(segA, segB);
  2598. if (l2 === 0.0) {
  2599. return Vector2.Distance(p, segA);
  2600. }
  2601. var v = segB.subtract(segA);
  2602. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2603. var proj = segA.add(v.multiplyByFloats(t, t));
  2604. return Vector2.Distance(p, proj);
  2605. };
  2606. return Vector2;
  2607. }());
  2608. BABYLON.Vector2 = Vector2;
  2609. /**
  2610. * Classed used to store (x,y,z) vector representation
  2611. * A Vector3 is the main object used in 3D geometry
  2612. * It can represent etiher the coordinates of a point the space, either a direction
  2613. * Reminder: Babylon.js uses a left handed forward facing system
  2614. */
  2615. var Vector3 = /** @class */ (function () {
  2616. /**
  2617. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2618. * @param x defines the first coordinates (on X axis)
  2619. * @param y defines the second coordinates (on Y axis)
  2620. * @param z defines the third coordinates (on Z axis)
  2621. */
  2622. function Vector3(
  2623. /**
  2624. * Defines the first coordinates (on X axis)
  2625. */
  2626. x,
  2627. /**
  2628. * Defines the second coordinates (on Y axis)
  2629. */
  2630. y,
  2631. /**
  2632. * Defines the third coordinates (on Z axis)
  2633. */
  2634. z) {
  2635. this.x = x;
  2636. this.y = y;
  2637. this.z = z;
  2638. }
  2639. /**
  2640. * Creates a string representation of the Vector3
  2641. * @returns a string with the Vector3 coordinates.
  2642. */
  2643. Vector3.prototype.toString = function () {
  2644. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2645. };
  2646. /**
  2647. * Gets the class name
  2648. * @returns the string "Vector3"
  2649. */
  2650. Vector3.prototype.getClassName = function () {
  2651. return "Vector3";
  2652. };
  2653. /**
  2654. * Creates the Vector3 hash code
  2655. * @returns a number which tends to be unique between Vector3 instances
  2656. */
  2657. Vector3.prototype.getHashCode = function () {
  2658. var hash = this.x || 0;
  2659. hash = (hash * 397) ^ (this.y || 0);
  2660. hash = (hash * 397) ^ (this.z || 0);
  2661. return hash;
  2662. };
  2663. // Operators
  2664. /**
  2665. * Creates an array containing three elements : the coordinates of the Vector3
  2666. * @returns a new array of numbers
  2667. */
  2668. Vector3.prototype.asArray = function () {
  2669. var result = [];
  2670. this.toArray(result, 0);
  2671. return result;
  2672. };
  2673. /**
  2674. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2675. * @param array defines the destination array
  2676. * @param index defines the offset in the destination array
  2677. * @returns the current Vector3
  2678. */
  2679. Vector3.prototype.toArray = function (array, index) {
  2680. if (index === void 0) { index = 0; }
  2681. array[index] = this.x;
  2682. array[index + 1] = this.y;
  2683. array[index + 2] = this.z;
  2684. return this;
  2685. };
  2686. /**
  2687. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2688. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2689. */
  2690. Vector3.prototype.toQuaternion = function () {
  2691. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2692. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2693. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2694. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2695. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2696. var cosy = Math.cos(this.y * 0.5);
  2697. var siny = Math.sin(this.y * 0.5);
  2698. result.x = coszMinusx * siny;
  2699. result.y = -sinzMinusx * siny;
  2700. result.z = sinxPlusz * cosy;
  2701. result.w = cosxPlusz * cosy;
  2702. return result;
  2703. };
  2704. /**
  2705. * Adds the given vector to the current Vector3
  2706. * @param otherVector defines the second operand
  2707. * @returns the current updated Vector3
  2708. */
  2709. Vector3.prototype.addInPlace = function (otherVector) {
  2710. this.x += otherVector.x;
  2711. this.y += otherVector.y;
  2712. this.z += otherVector.z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2717. * @param otherVector defines the second operand
  2718. * @returns the resulting Vector3
  2719. */
  2720. Vector3.prototype.add = function (otherVector) {
  2721. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2722. };
  2723. /**
  2724. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2725. * @param otherVector defines the second operand
  2726. * @param result defines the Vector3 object where to store the result
  2727. * @returns the current Vector3
  2728. */
  2729. Vector3.prototype.addToRef = function (otherVector, result) {
  2730. result.x = this.x + otherVector.x;
  2731. result.y = this.y + otherVector.y;
  2732. result.z = this.z + otherVector.z;
  2733. return this;
  2734. };
  2735. /**
  2736. * Subtract the given vector from the current Vector3
  2737. * @param otherVector defines the second operand
  2738. * @returns the current updated Vector3
  2739. */
  2740. Vector3.prototype.subtractInPlace = function (otherVector) {
  2741. this.x -= otherVector.x;
  2742. this.y -= otherVector.y;
  2743. this.z -= otherVector.z;
  2744. return this;
  2745. };
  2746. /**
  2747. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2748. * @param otherVector defines the second operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtract = function (otherVector) {
  2752. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2753. };
  2754. /**
  2755. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2756. * @param otherVector defines the second operand
  2757. * @param result defines the Vector3 object where to store the result
  2758. * @returns the current Vector3
  2759. */
  2760. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2761. result.x = this.x - otherVector.x;
  2762. result.y = this.y - otherVector.y;
  2763. result.z = this.z - otherVector.z;
  2764. return this;
  2765. };
  2766. /**
  2767. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2768. * @param x defines the x coordinate of the operand
  2769. * @param y defines the y coordinate of the operand
  2770. * @param z defines the z coordinate of the operand
  2771. * @returns the resulting Vector3
  2772. */
  2773. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2774. return new Vector3(this.x - x, this.y - y, this.z - z);
  2775. };
  2776. /**
  2777. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2778. * @param x defines the x coordinate of the operand
  2779. * @param y defines the y coordinate of the operand
  2780. * @param z defines the z coordinate of the operand
  2781. * @param result defines the Vector3 object where to store the result
  2782. * @returns the current Vector3
  2783. */
  2784. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2785. result.x = this.x - x;
  2786. result.y = this.y - y;
  2787. result.z = this.z - z;
  2788. return this;
  2789. };
  2790. /**
  2791. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2792. * @returns a new Vector3
  2793. */
  2794. Vector3.prototype.negate = function () {
  2795. return new Vector3(-this.x, -this.y, -this.z);
  2796. };
  2797. /**
  2798. * Multiplies the Vector3 coordinates by the float "scale"
  2799. * @param scale defines the multiplier factor
  2800. * @returns the current updated Vector3
  2801. */
  2802. Vector3.prototype.scaleInPlace = function (scale) {
  2803. this.x *= scale;
  2804. this.y *= scale;
  2805. this.z *= scale;
  2806. return this;
  2807. };
  2808. /**
  2809. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2810. * @param scale defines the multiplier factor
  2811. * @returns a new Vector3
  2812. */
  2813. Vector3.prototype.scale = function (scale) {
  2814. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2818. * @param scale defines the multiplier factor
  2819. * @param result defines the Vector3 object where to store the result
  2820. * @returns the current Vector3
  2821. */
  2822. Vector3.prototype.scaleToRef = function (scale, result) {
  2823. result.x = this.x * scale;
  2824. result.y = this.y * scale;
  2825. result.z = this.z * scale;
  2826. return this;
  2827. };
  2828. /**
  2829. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2830. * @param scale defines the scale factor
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the unmodified current Vector3
  2833. */
  2834. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2835. result.x += this.x * scale;
  2836. result.y += this.y * scale;
  2837. result.z += this.z * scale;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2842. * @param otherVector defines the second operand
  2843. * @returns true if both vectors are equals
  2844. */
  2845. Vector3.prototype.equals = function (otherVector) {
  2846. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2847. };
  2848. /**
  2849. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2850. * @param otherVector defines the second operand
  2851. * @param epsilon defines the minimal distance to define values as equals
  2852. * @returns true if both vectors are distant less than epsilon
  2853. */
  2854. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2855. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2856. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2857. };
  2858. /**
  2859. * Returns true if the current Vector3 coordinates equals the given floats
  2860. * @param x defines the x coordinate of the operand
  2861. * @param y defines the y coordinate of the operand
  2862. * @param z defines the z coordinate of the operand
  2863. * @returns true if both vectors are equals
  2864. */
  2865. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2866. return this.x === x && this.y === y && this.z === z;
  2867. };
  2868. /**
  2869. * Multiplies the current Vector3 coordinates by the given ones
  2870. * @param otherVector defines the second operand
  2871. * @returns the current updated Vector3
  2872. */
  2873. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2874. this.x *= otherVector.x;
  2875. this.y *= otherVector.y;
  2876. this.z *= otherVector.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2881. * @param otherVector defines the second operand
  2882. * @returns the new Vector3
  2883. */
  2884. Vector3.prototype.multiply = function (otherVector) {
  2885. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2886. };
  2887. /**
  2888. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2889. * @param otherVector defines the second operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2894. result.x = this.x * otherVector.x;
  2895. result.y = this.y * otherVector.y;
  2896. result.z = this.z * otherVector.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  2901. * @param x defines the x coordinate of the operand
  2902. * @param y defines the y coordinate of the operand
  2903. * @param z defines the z coordinate of the operand
  2904. * @returns the new Vector3
  2905. */
  2906. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2907. return new Vector3(this.x * x, this.y * y, this.z * z);
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  2911. * @param otherVector defines the second operand
  2912. * @returns the new Vector3
  2913. */
  2914. Vector3.prototype.divide = function (otherVector) {
  2915. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2916. };
  2917. /**
  2918. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.divideToRef = function (otherVector, result) {
  2924. result.x = this.x / otherVector.x;
  2925. result.y = this.y / otherVector.y;
  2926. result.z = this.z / otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Divides the current Vector3 coordinates by the given ones.
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.divideInPlace = function (otherVector) {
  2935. return this.divideToRef(otherVector, this);
  2936. };
  2937. /**
  2938. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  2939. * @param other defines the second operand
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.minimizeInPlace = function (other) {
  2943. if (other.x < this.x)
  2944. this.x = other.x;
  2945. if (other.y < this.y)
  2946. this.y = other.y;
  2947. if (other.z < this.z)
  2948. this.z = other.z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  2953. * @param other defines the second operand
  2954. * @returns the current updated Vector3
  2955. */
  2956. Vector3.prototype.maximizeInPlace = function (other) {
  2957. if (other.x > this.x)
  2958. this.x = other.x;
  2959. if (other.y > this.y)
  2960. this.y = other.y;
  2961. if (other.z > this.z)
  2962. this.z = other.z;
  2963. return this;
  2964. };
  2965. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2966. /**
  2967. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2968. */
  2969. get: function () {
  2970. var absX = Math.abs(this.x);
  2971. var absY = Math.abs(this.y);
  2972. if (absX !== absY) {
  2973. return true;
  2974. }
  2975. var absZ = Math.abs(this.z);
  2976. if (absX !== absZ) {
  2977. return true;
  2978. }
  2979. if (absY !== absZ) {
  2980. return true;
  2981. }
  2982. return false;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. // Properties
  2988. /**
  2989. * Gets the length of the Vector3
  2990. * @returns the length of the Vecto3
  2991. */
  2992. Vector3.prototype.length = function () {
  2993. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2994. };
  2995. /**
  2996. * Gets the squared length of the Vector3
  2997. * @returns squared length of the Vector3
  2998. */
  2999. Vector3.prototype.lengthSquared = function () {
  3000. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3001. };
  3002. /**
  3003. * Normalize the current Vector3.
  3004. * Please note that this is an in place operation.
  3005. * @returns the current updated Vector3
  3006. */
  3007. Vector3.prototype.normalize = function () {
  3008. var len = this.length();
  3009. if (len === 0 || len === 1.0)
  3010. return this;
  3011. var num = 1.0 / len;
  3012. this.x *= num;
  3013. this.y *= num;
  3014. this.z *= num;
  3015. return this;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to a new vector
  3019. * @returns the new Vector3
  3020. */
  3021. Vector3.prototype.normalizeToNew = function () {
  3022. var normalized = new Vector3(0, 0, 0);
  3023. this.normalizeToRef(normalized);
  3024. return normalized;
  3025. };
  3026. /**
  3027. * Normalize the current Vector3 to the reference
  3028. * @param reference define the Vector3 to update
  3029. * @returns the updated Vector3
  3030. */
  3031. Vector3.prototype.normalizeToRef = function (reference) {
  3032. var len = this.length();
  3033. if (len === 0 || len === 1.0) {
  3034. reference.set(this.x, this.y, this.z);
  3035. return reference;
  3036. }
  3037. var scale = 1.0 / len;
  3038. this.scaleToRef(scale, reference);
  3039. return reference;
  3040. };
  3041. /**
  3042. * Creates a new Vector3 copied from the current Vector3
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.clone = function () {
  3046. return new Vector3(this.x, this.y, this.z);
  3047. };
  3048. /**
  3049. * Copies the given vector coordinates to the current Vector3 ones
  3050. * @param source defines the source Vector3
  3051. * @returns the current updated Vector3
  3052. */
  3053. Vector3.prototype.copyFrom = function (source) {
  3054. this.x = source.x;
  3055. this.y = source.y;
  3056. this.z = source.z;
  3057. return this;
  3058. };
  3059. /**
  3060. * Copies the given floats to the current Vector3 coordinates
  3061. * @param x defines the x coordinate of the operand
  3062. * @param y defines the y coordinate of the operand
  3063. * @param z defines the z coordinate of the operand
  3064. * @returns the current updated Vector3
  3065. */
  3066. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3067. this.x = x;
  3068. this.y = y;
  3069. this.z = z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Copies the given floats to the current Vector3 coordinates
  3074. * @param x defines the x coordinate of the operand
  3075. * @param y defines the y coordinate of the operand
  3076. * @param z defines the z coordinate of the operand
  3077. * @returns the current updated Vector3
  3078. */
  3079. Vector3.prototype.set = function (x, y, z) {
  3080. return this.copyFromFloats(x, y, z);
  3081. };
  3082. // Statics
  3083. /**
  3084. * Get the clip factor between two vectors
  3085. * @param vector0 defines the first operand
  3086. * @param vector1 defines the second operand
  3087. * @param axis defines the axis to use
  3088. * @param size defines the size along the axis
  3089. * @returns the clip factor
  3090. */
  3091. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3092. var d0 = Vector3.Dot(vector0, axis) - size;
  3093. var d1 = Vector3.Dot(vector1, axis) - size;
  3094. var s = d0 / (d0 - d1);
  3095. return s;
  3096. };
  3097. /**
  3098. * Get angle between two vectors
  3099. * @param vector0 angle between vector0 and vector1
  3100. * @param vector1 angle between vector0 and vector1
  3101. * @param normal direction of the normal
  3102. * @return the angle between vector0 and vector1
  3103. */
  3104. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3105. var v0 = vector0.clone().normalize();
  3106. var v1 = vector1.clone().normalize();
  3107. var dot = Vector3.Dot(v0, v1);
  3108. var n = Vector3.Cross(v0, v1);
  3109. if (Vector3.Dot(n, normal) > 0) {
  3110. return Math.acos(dot);
  3111. }
  3112. return -Math.acos(dot);
  3113. };
  3114. /**
  3115. * Returns a new Vector3 set from the index "offset" of the given array
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @returns the new Vector3
  3119. */
  3120. Vector3.FromArray = function (array, offset) {
  3121. if (!offset) {
  3122. offset = 0;
  3123. }
  3124. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3125. };
  3126. /**
  3127. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3128. * This function is deprecated. Use FromArray instead
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.FromFloatArray = function (array, offset) {
  3134. return Vector3.FromArray(array, offset);
  3135. };
  3136. /**
  3137. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3138. * @param array defines the source array
  3139. * @param offset defines the offset in the source array
  3140. * @param result defines the Vector3 where to store the result
  3141. */
  3142. Vector3.FromArrayToRef = function (array, offset, result) {
  3143. result.x = array[offset];
  3144. result.y = array[offset + 1];
  3145. result.z = array[offset + 2];
  3146. };
  3147. /**
  3148. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3149. * This function is deprecated. Use FromArrayToRef instead.
  3150. * @param array defines the source array
  3151. * @param offset defines the offset in the source array
  3152. * @param result defines the Vector3 where to store the result
  3153. */
  3154. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3155. return Vector3.FromArrayToRef(array, offset, result);
  3156. };
  3157. /**
  3158. * Sets the given vector "result" with the given floats.
  3159. * @param x defines the x coordinate of the source
  3160. * @param y defines the y coordinate of the source
  3161. * @param z defines the z coordinate of the source
  3162. * @param result defines the Vector3 where to store the result
  3163. */
  3164. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3165. result.x = x;
  3166. result.y = y;
  3167. result.z = z;
  3168. };
  3169. /**
  3170. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3171. * @returns a new empty Vector3
  3172. */
  3173. Vector3.Zero = function () {
  3174. return new Vector3(0.0, 0.0, 0.0);
  3175. };
  3176. /**
  3177. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3178. * @returns a new unit Vector3
  3179. */
  3180. Vector3.One = function () {
  3181. return new Vector3(1.0, 1.0, 1.0);
  3182. };
  3183. /**
  3184. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3185. * @returns a new up Vector3
  3186. */
  3187. Vector3.Up = function () {
  3188. return new Vector3(0.0, 1.0, 0.0);
  3189. };
  3190. /**
  3191. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3192. * @returns a new forward Vector3
  3193. */
  3194. Vector3.Forward = function () {
  3195. return new Vector3(0.0, 0.0, 1.0);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3199. * @returns a new right Vector3
  3200. */
  3201. Vector3.Right = function () {
  3202. return new Vector3(1.0, 0.0, 0.0);
  3203. };
  3204. /**
  3205. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3206. * @returns a new left Vector3
  3207. */
  3208. Vector3.Left = function () {
  3209. return new Vector3(-1.0, 0.0, 0.0);
  3210. };
  3211. /**
  3212. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3213. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3214. * @param vector defines the Vector3 to transform
  3215. * @param transformation defines the transformation matrix
  3216. * @returns the transformed Vector3
  3217. */
  3218. Vector3.TransformCoordinates = function (vector, transformation) {
  3219. var result = Vector3.Zero();
  3220. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3225. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @param result defines the Vector3 where to store the result
  3229. */
  3230. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3231. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3232. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3233. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3234. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3235. result.x = x / w;
  3236. result.y = y / w;
  3237. result.z = z / w;
  3238. };
  3239. /**
  3240. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3241. * This method computes tranformed coordinates only, not transformed direction vectors
  3242. * @param x define the x coordinate of the source vector
  3243. * @param y define the y coordinate of the source vector
  3244. * @param z define the z coordinate of the source vector
  3245. * @param transformation defines the transformation matrix
  3246. * @param result defines the Vector3 where to store the result
  3247. */
  3248. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3249. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3250. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3251. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3252. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3253. result.x = rx / rw;
  3254. result.y = ry / rw;
  3255. result.z = rz / rw;
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3259. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3260. * @param vector defines the Vector3 to transform
  3261. * @param transformation defines the transformation matrix
  3262. * @returns the new Vector3
  3263. */
  3264. Vector3.TransformNormal = function (vector, transformation) {
  3265. var result = Vector3.Zero();
  3266. Vector3.TransformNormalToRef(vector, transformation, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3271. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3272. * @param vector defines the Vector3 to transform
  3273. * @param transformation defines the transformation matrix
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3277. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3278. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3279. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3280. result.x = x;
  3281. result.y = y;
  3282. result.z = z;
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3286. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3287. * @param x define the x coordinate of the source vector
  3288. * @param y define the y coordinate of the source vector
  3289. * @param z define the z coordinate of the source vector
  3290. * @param transformation defines the transformation matrix
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3294. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3295. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3296. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3297. };
  3298. /**
  3299. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3300. * @param value1 defines the first control point
  3301. * @param value2 defines the second control point
  3302. * @param value3 defines the third control point
  3303. * @param value4 defines the fourth control point
  3304. * @param amount defines the amount on the spline to use
  3305. * @returns the new Vector3
  3306. */
  3307. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3308. var squared = amount * amount;
  3309. var cubed = amount * squared;
  3310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3311. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3312. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3313. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3314. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3315. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3316. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3317. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3318. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3319. return new Vector3(x, y, z);
  3320. };
  3321. /**
  3322. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3323. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3324. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3325. * @param value defines the current value
  3326. * @param min defines the lower range value
  3327. * @param max defines the upper range value
  3328. * @returns the new Vector3
  3329. */
  3330. Vector3.Clamp = function (value, min, max) {
  3331. var x = value.x;
  3332. x = (x > max.x) ? max.x : x;
  3333. x = (x < min.x) ? min.x : x;
  3334. var y = value.y;
  3335. y = (y > max.y) ? max.y : y;
  3336. y = (y < min.y) ? min.y : y;
  3337. var z = value.z;
  3338. z = (z > max.z) ? max.z : z;
  3339. z = (z < min.z) ? min.z : z;
  3340. return new Vector3(x, y, z);
  3341. };
  3342. /**
  3343. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3344. * @param value1 defines the first control point
  3345. * @param tangent1 defines the first tangent vector
  3346. * @param value2 defines the second control point
  3347. * @param tangent2 defines the second tangent vector
  3348. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3352. var squared = amount * amount;
  3353. var cubed = amount * squared;
  3354. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3355. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3356. var part3 = (cubed - (2.0 * squared)) + amount;
  3357. var part4 = cubed - squared;
  3358. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3359. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3360. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3361. return new Vector3(x, y, z);
  3362. };
  3363. /**
  3364. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3365. * @param start defines the start value
  3366. * @param end defines the end value
  3367. * @param amount max defines amount between both (between 0 and 1)
  3368. * @returns the new Vector3
  3369. */
  3370. Vector3.Lerp = function (start, end, amount) {
  3371. var result = new Vector3(0, 0, 0);
  3372. Vector3.LerpToRef(start, end, amount, result);
  3373. return result;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3377. * @param start defines the start value
  3378. * @param end defines the end value
  3379. * @param amount max defines amount between both (between 0 and 1)
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.LerpToRef = function (start, end, amount, result) {
  3383. result.x = start.x + ((end.x - start.x) * amount);
  3384. result.y = start.y + ((end.y - start.y) * amount);
  3385. result.z = start.z + ((end.z - start.z) * amount);
  3386. };
  3387. /**
  3388. * Returns the dot product (float) between the vectors "left" and "right"
  3389. * @param left defines the left operand
  3390. * @param right defines the right operand
  3391. * @returns the dot product
  3392. */
  3393. Vector3.Dot = function (left, right) {
  3394. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3395. };
  3396. /**
  3397. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3398. * The cross product is then orthogonal to both "left" and "right"
  3399. * @param left defines the left operand
  3400. * @param right defines the right operand
  3401. * @returns the cross product
  3402. */
  3403. Vector3.Cross = function (left, right) {
  3404. var result = Vector3.Zero();
  3405. Vector3.CrossToRef(left, right, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the cross product of "left" and "right"
  3410. * The cross product is then orthogonal to both "left" and "right"
  3411. * @param left defines the left operand
  3412. * @param right defines the right operand
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.CrossToRef = function (left, right, result) {
  3416. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3417. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3418. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3419. result.copyFrom(MathTmp.Vector3[0]);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 as the normalization of the given vector
  3423. * @param vector defines the Vector3 to normalize
  3424. * @returns the new Vector3
  3425. */
  3426. Vector3.Normalize = function (vector) {
  3427. var result = Vector3.Zero();
  3428. Vector3.NormalizeToRef(vector, result);
  3429. return result;
  3430. };
  3431. /**
  3432. * Sets the given vector "result" with the normalization of the given first vector
  3433. * @param vector defines the Vector3 to normalize
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.NormalizeToRef = function (vector, result) {
  3437. result.copyFrom(vector);
  3438. result.normalize();
  3439. };
  3440. /**
  3441. * Project a Vector3 onto screen space
  3442. * @param vector defines the Vector3 to project
  3443. * @param world defines the world matrix to use
  3444. * @param transform defines the transform (view x projection) matrix to use
  3445. * @param viewport defines the screen viewport to use
  3446. * @returns the new Vector3
  3447. */
  3448. Vector3.Project = function (vector, world, transform, viewport) {
  3449. var cw = viewport.width;
  3450. var ch = viewport.height;
  3451. var cx = viewport.x;
  3452. var cy = viewport.y;
  3453. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3454. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3455. var matrix = MathTmp.Matrix[0];
  3456. world.multiplyToRef(transform, matrix);
  3457. matrix.multiplyToRef(viewportMatrix, matrix);
  3458. return Vector3.TransformCoordinates(vector, matrix);
  3459. };
  3460. /**
  3461. * Unproject from screen space to object space
  3462. * @param source defines the screen space Vector3 to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param transform defines the transform (view x projection) matrix to use
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3470. var matrix = MathTmp.Matrix[0];
  3471. world.multiplyToRef(transform, matrix);
  3472. matrix.invert();
  3473. source.x = source.x / viewportWidth * 2 - 1;
  3474. source.y = -(source.y / viewportHeight * 2 - 1);
  3475. var vector = Vector3.TransformCoordinates(source, matrix);
  3476. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3477. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3478. vector = vector.scale(1.0 / num);
  3479. }
  3480. return vector;
  3481. };
  3482. /**
  3483. * Unproject from screen space to object space
  3484. * @param source defines the screen space Vector3 to use
  3485. * @param viewportWidth defines the current width of the viewport
  3486. * @param viewportHeight defines the current height of the viewport
  3487. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3488. * @param view defines the view matrix to use
  3489. * @param projection defines the projection matrix to use
  3490. * @returns the new Vector3
  3491. */
  3492. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3493. var result = Vector3.Zero();
  3494. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3495. return result;
  3496. };
  3497. /**
  3498. * Unproject from screen space to object space
  3499. * @param source defines the screen space Vector3 to use
  3500. * @param viewportWidth defines the current width of the viewport
  3501. * @param viewportHeight defines the current height of the viewport
  3502. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3503. * @param view defines the view matrix to use
  3504. * @param projection defines the projection matrix to use
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3508. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3509. };
  3510. /**
  3511. * Unproject from screen space to object space
  3512. * @param sourceX defines the screen space x coordinate to use
  3513. * @param sourceY defines the screen space y coordinate to use
  3514. * @param sourceZ defines the screen space z coordinate to use
  3515. * @param viewportWidth defines the current width of the viewport
  3516. * @param viewportHeight defines the current height of the viewport
  3517. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3518. * @param view defines the view matrix to use
  3519. * @param projection defines the projection matrix to use
  3520. * @param result defines the Vector3 where to store the result
  3521. */
  3522. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3523. var matrix = MathTmp.Matrix[0];
  3524. world.multiplyToRef(view, matrix);
  3525. matrix.multiplyToRef(projection, matrix);
  3526. matrix.invert();
  3527. var screenSource = MathTmp.Vector3[0];
  3528. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3529. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3530. screenSource.z = 2 * sourceZ - 1.0;
  3531. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3532. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3533. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3534. result.scaleInPlace(1.0 / num);
  3535. }
  3536. };
  3537. /**
  3538. * Gets the minimal coordinate values between two Vector3
  3539. * @param left defines the first operand
  3540. * @param right defines the second operand
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.Minimize = function (left, right) {
  3544. var min = left.clone();
  3545. min.minimizeInPlace(right);
  3546. return min;
  3547. };
  3548. /**
  3549. * Gets the maximal coordinate values between two Vector3
  3550. * @param left defines the first operand
  3551. * @param right defines the second operand
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Maximize = function (left, right) {
  3555. var max = left.clone();
  3556. max.maximizeInPlace(right);
  3557. return max;
  3558. };
  3559. /**
  3560. * Returns the distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the distance
  3564. */
  3565. Vector3.Distance = function (value1, value2) {
  3566. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3567. };
  3568. /**
  3569. * Returns the squared distance between the vectors "value1" and "value2"
  3570. * @param value1 defines the first operand
  3571. * @param value2 defines the second operand
  3572. * @returns the squared distance
  3573. */
  3574. Vector3.DistanceSquared = function (value1, value2) {
  3575. var x = value1.x - value2.x;
  3576. var y = value1.y - value2.y;
  3577. var z = value1.z - value2.z;
  3578. return (x * x) + (y * y) + (z * z);
  3579. };
  3580. /**
  3581. * Returns a new Vector3 located at the center between "value1" and "value2"
  3582. * @param value1 defines the first operand
  3583. * @param value2 defines the second operand
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.Center = function (value1, value2) {
  3587. var center = value1.add(value2);
  3588. center.scaleInPlace(0.5);
  3589. return center;
  3590. };
  3591. /**
  3592. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3593. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3594. * to something in order to rotate it from its local system to the given target system
  3595. * Note: axis1, axis2 and axis3 are normalized during this operation
  3596. * @param axis1 defines the first axis
  3597. * @param axis2 defines the second axis
  3598. * @param axis3 defines the third axis
  3599. * @returns a new Vector3
  3600. */
  3601. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3602. var rotation = Vector3.Zero();
  3603. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3604. return rotation;
  3605. };
  3606. /**
  3607. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3608. * @param axis1 defines the first axis
  3609. * @param axis2 defines the second axis
  3610. * @param axis3 defines the third axis
  3611. * @param ref defines the Vector3 where to store the result
  3612. */
  3613. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3614. var quat = MathTmp.Quaternion[0];
  3615. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3616. quat.toEulerAnglesToRef(ref);
  3617. };
  3618. return Vector3;
  3619. }());
  3620. BABYLON.Vector3 = Vector3;
  3621. //Vector4 class created for EulerAngle class conversion to Quaternion
  3622. var Vector4 = /** @class */ (function () {
  3623. /**
  3624. * Creates a Vector4 object from the given floats.
  3625. */
  3626. function Vector4(x, y, z, w) {
  3627. this.x = x;
  3628. this.y = y;
  3629. this.z = z;
  3630. this.w = w;
  3631. }
  3632. /**
  3633. * Returns the string with the Vector4 coordinates.
  3634. */
  3635. Vector4.prototype.toString = function () {
  3636. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3637. };
  3638. /**
  3639. * Returns the string "Vector4".
  3640. */
  3641. Vector4.prototype.getClassName = function () {
  3642. return "Vector4";
  3643. };
  3644. /**
  3645. * Returns the Vector4 hash code.
  3646. */
  3647. Vector4.prototype.getHashCode = function () {
  3648. var hash = this.x || 0;
  3649. hash = (hash * 397) ^ (this.y || 0);
  3650. hash = (hash * 397) ^ (this.z || 0);
  3651. hash = (hash * 397) ^ (this.w || 0);
  3652. return hash;
  3653. };
  3654. // Operators
  3655. /**
  3656. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3657. */
  3658. Vector4.prototype.asArray = function () {
  3659. var result = new Array();
  3660. this.toArray(result, 0);
  3661. return result;
  3662. };
  3663. /**
  3664. * Populates the given array from the given index with the Vector4 coordinates.
  3665. * Returns the Vector4.
  3666. */
  3667. Vector4.prototype.toArray = function (array, index) {
  3668. if (index === undefined) {
  3669. index = 0;
  3670. }
  3671. array[index] = this.x;
  3672. array[index + 1] = this.y;
  3673. array[index + 2] = this.z;
  3674. array[index + 3] = this.w;
  3675. return this;
  3676. };
  3677. /**
  3678. * Adds the given vector to the current Vector4.
  3679. * Returns the updated Vector4.
  3680. */
  3681. Vector4.prototype.addInPlace = function (otherVector) {
  3682. this.x += otherVector.x;
  3683. this.y += otherVector.y;
  3684. this.z += otherVector.z;
  3685. this.w += otherVector.w;
  3686. return this;
  3687. };
  3688. /**
  3689. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3690. */
  3691. Vector4.prototype.add = function (otherVector) {
  3692. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3693. };
  3694. /**
  3695. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3696. * Returns the current Vector4.
  3697. */
  3698. Vector4.prototype.addToRef = function (otherVector, result) {
  3699. result.x = this.x + otherVector.x;
  3700. result.y = this.y + otherVector.y;
  3701. result.z = this.z + otherVector.z;
  3702. result.w = this.w + otherVector.w;
  3703. return this;
  3704. };
  3705. /**
  3706. * Subtract in place the given vector from the current Vector4.
  3707. * Returns the updated Vector4.
  3708. */
  3709. Vector4.prototype.subtractInPlace = function (otherVector) {
  3710. this.x -= otherVector.x;
  3711. this.y -= otherVector.y;
  3712. this.z -= otherVector.z;
  3713. this.w -= otherVector.w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3718. */
  3719. Vector4.prototype.subtract = function (otherVector) {
  3720. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3721. };
  3722. /**
  3723. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3724. * Returns the current Vector4.
  3725. */
  3726. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3727. result.x = this.x - otherVector.x;
  3728. result.y = this.y - otherVector.y;
  3729. result.z = this.z - otherVector.z;
  3730. result.w = this.w - otherVector.w;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3735. */
  3736. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3737. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3738. };
  3739. /**
  3740. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3744. result.x = this.x - x;
  3745. result.y = this.y - y;
  3746. result.z = this.z - z;
  3747. result.w = this.w - w;
  3748. return this;
  3749. };
  3750. /**
  3751. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3752. */
  3753. Vector4.prototype.negate = function () {
  3754. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3755. };
  3756. /**
  3757. * Multiplies the current Vector4 coordinates by scale (float).
  3758. * Returns the updated Vector4.
  3759. */
  3760. Vector4.prototype.scaleInPlace = function (scale) {
  3761. this.x *= scale;
  3762. this.y *= scale;
  3763. this.z *= scale;
  3764. this.w *= scale;
  3765. return this;
  3766. };
  3767. /**
  3768. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3769. */
  3770. Vector4.prototype.scale = function (scale) {
  3771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3772. };
  3773. /**
  3774. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3775. * Returns the current Vector4.
  3776. */
  3777. Vector4.prototype.scaleToRef = function (scale, result) {
  3778. result.x = this.x * scale;
  3779. result.y = this.y * scale;
  3780. result.z = this.z * scale;
  3781. result.w = this.w * scale;
  3782. return this;
  3783. };
  3784. /**
  3785. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3786. * @param scale defines the scale factor
  3787. * @param result defines the Vector4 object where to store the result
  3788. * @returns the unmodified current Vector4
  3789. */
  3790. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3791. result.x += this.x * scale;
  3792. result.y += this.y * scale;
  3793. result.z += this.z * scale;
  3794. result.w += this.w * scale;
  3795. return this;
  3796. };
  3797. /**
  3798. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3799. */
  3800. Vector4.prototype.equals = function (otherVector) {
  3801. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3802. };
  3803. /**
  3804. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3805. */
  3806. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3807. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3808. return otherVector
  3809. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3810. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3811. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3812. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3813. };
  3814. /**
  3815. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3818. return this.x === x && this.y === y && this.z === z && this.w === w;
  3819. };
  3820. /**
  3821. * Multiplies in place the current Vector4 by the given one.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3825. this.x *= otherVector.x;
  3826. this.y *= otherVector.y;
  3827. this.z *= otherVector.z;
  3828. this.w *= otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.multiply = function (otherVector) {
  3835. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3842. result.x = this.x * otherVector.x;
  3843. result.y = this.y * otherVector.y;
  3844. result.z = this.z * otherVector.z;
  3845. result.w = this.w * otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3850. */
  3851. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3852. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3853. };
  3854. /**
  3855. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3856. */
  3857. Vector4.prototype.divide = function (otherVector) {
  3858. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3859. };
  3860. /**
  3861. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3862. * Returns the current Vector4.
  3863. */
  3864. Vector4.prototype.divideToRef = function (otherVector, result) {
  3865. result.x = this.x / otherVector.x;
  3866. result.y = this.y / otherVector.y;
  3867. result.z = this.z / otherVector.z;
  3868. result.w = this.w / otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Divides the current Vector3 coordinates by the given ones.
  3873. * @returns the updated Vector3.
  3874. */
  3875. Vector4.prototype.divideInPlace = function (otherVector) {
  3876. return this.divideToRef(otherVector, this);
  3877. };
  3878. /**
  3879. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3880. * @param other defines the second operand
  3881. * @returns the current updated Vector4
  3882. */
  3883. Vector4.prototype.minimizeInPlace = function (other) {
  3884. if (other.x < this.x)
  3885. this.x = other.x;
  3886. if (other.y < this.y)
  3887. this.y = other.y;
  3888. if (other.z < this.z)
  3889. this.z = other.z;
  3890. if (other.w < this.w)
  3891. this.w = other.w;
  3892. return this;
  3893. };
  3894. /**
  3895. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  3896. * @param other defines the second operand
  3897. * @returns the current updated Vector4
  3898. */
  3899. Vector4.prototype.maximizeInPlace = function (other) {
  3900. if (other.x > this.x)
  3901. this.x = other.x;
  3902. if (other.y > this.y)
  3903. this.y = other.y;
  3904. if (other.z > this.z)
  3905. this.z = other.z;
  3906. if (other.w > this.w)
  3907. this.w = other.w;
  3908. return this;
  3909. };
  3910. // Properties
  3911. /**
  3912. * Returns the Vector4 length (float).
  3913. */
  3914. Vector4.prototype.length = function () {
  3915. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3916. };
  3917. /**
  3918. * Returns the Vector4 squared length (float).
  3919. */
  3920. Vector4.prototype.lengthSquared = function () {
  3921. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3922. };
  3923. // Methods
  3924. /**
  3925. * Normalizes in place the Vector4.
  3926. * Returns the updated Vector4.
  3927. */
  3928. Vector4.prototype.normalize = function () {
  3929. var len = this.length();
  3930. if (len === 0)
  3931. return this;
  3932. var num = 1.0 / len;
  3933. this.x *= num;
  3934. this.y *= num;
  3935. this.z *= num;
  3936. this.w *= num;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3941. */
  3942. Vector4.prototype.toVector3 = function () {
  3943. return new Vector3(this.x, this.y, this.z);
  3944. };
  3945. /**
  3946. * Returns a new Vector4 copied from the current one.
  3947. */
  3948. Vector4.prototype.clone = function () {
  3949. return new Vector4(this.x, this.y, this.z, this.w);
  3950. };
  3951. /**
  3952. * Updates the current Vector4 with the given one coordinates.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.copyFrom = function (source) {
  3956. this.x = source.x;
  3957. this.y = source.y;
  3958. this.z = source.z;
  3959. this.w = source.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Updates the current Vector4 coordinates with the given floats.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3967. this.x = x;
  3968. this.y = y;
  3969. this.z = z;
  3970. this.w = w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Updates the current Vector4 coordinates with the given floats.
  3975. * Returns the updated Vector4.
  3976. */
  3977. Vector4.prototype.set = function (x, y, z, w) {
  3978. return this.copyFromFloats(x, y, z, w);
  3979. };
  3980. // Statics
  3981. /**
  3982. * Returns a new Vector4 set from the starting index of the given array.
  3983. */
  3984. Vector4.FromArray = function (array, offset) {
  3985. if (!offset) {
  3986. offset = 0;
  3987. }
  3988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3989. };
  3990. /**
  3991. * Updates the given vector "result" from the starting index of the given array.
  3992. */
  3993. Vector4.FromArrayToRef = function (array, offset, result) {
  3994. result.x = array[offset];
  3995. result.y = array[offset + 1];
  3996. result.z = array[offset + 2];
  3997. result.w = array[offset + 3];
  3998. };
  3999. /**
  4000. * Updates the given vector "result" from the starting index of the given Float32Array.
  4001. */
  4002. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4003. Vector4.FromArrayToRef(array, offset, result);
  4004. };
  4005. /**
  4006. * Updates the given vector "result" coordinates from the given floats.
  4007. */
  4008. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4009. result.x = x;
  4010. result.y = y;
  4011. result.z = z;
  4012. result.w = w;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4016. */
  4017. Vector4.Zero = function () {
  4018. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4022. */
  4023. Vector4.One = function () {
  4024. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4025. };
  4026. /**
  4027. * Returns a new normalized Vector4 from the given one.
  4028. */
  4029. Vector4.Normalize = function (vector) {
  4030. var result = Vector4.Zero();
  4031. Vector4.NormalizeToRef(vector, result);
  4032. return result;
  4033. };
  4034. /**
  4035. * Updates the given vector "result" from the normalization of the given one.
  4036. */
  4037. Vector4.NormalizeToRef = function (vector, result) {
  4038. result.copyFrom(vector);
  4039. result.normalize();
  4040. };
  4041. Vector4.Minimize = function (left, right) {
  4042. var min = left.clone();
  4043. min.minimizeInPlace(right);
  4044. return min;
  4045. };
  4046. Vector4.Maximize = function (left, right) {
  4047. var max = left.clone();
  4048. max.maximizeInPlace(right);
  4049. return max;
  4050. };
  4051. /**
  4052. * Returns the distance (float) between the vectors "value1" and "value2".
  4053. */
  4054. Vector4.Distance = function (value1, value2) {
  4055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4056. };
  4057. /**
  4058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4059. */
  4060. Vector4.DistanceSquared = function (value1, value2) {
  4061. var x = value1.x - value2.x;
  4062. var y = value1.y - value2.y;
  4063. var z = value1.z - value2.z;
  4064. var w = value1.w - value2.w;
  4065. return (x * x) + (y * y) + (z * z) + (w * w);
  4066. };
  4067. /**
  4068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4069. */
  4070. Vector4.Center = function (value1, value2) {
  4071. var center = value1.add(value2);
  4072. center.scaleInPlace(0.5);
  4073. return center;
  4074. };
  4075. /**
  4076. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormal = function (vector, transformation) {
  4080. var result = Vector4.Zero();
  4081. Vector4.TransformNormalToRef(vector, transformation, result);
  4082. return result;
  4083. };
  4084. /**
  4085. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4086. * This methods computes transformed normalized direction vectors only.
  4087. */
  4088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4092. result.x = x;
  4093. result.y = y;
  4094. result.z = z;
  4095. result.w = vector.w;
  4096. };
  4097. /**
  4098. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4099. * This methods computes transformed normalized direction vectors only.
  4100. */
  4101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4105. result.w = w;
  4106. };
  4107. return Vector4;
  4108. }());
  4109. BABYLON.Vector4 = Vector4;
  4110. var Size = /** @class */ (function () {
  4111. /**
  4112. * Creates a Size object from the given width and height (floats).
  4113. */
  4114. function Size(width, height) {
  4115. this.width = width;
  4116. this.height = height;
  4117. }
  4118. // Returns a string with the Size width and height.
  4119. Size.prototype.toString = function () {
  4120. return "{W: " + this.width + ", H: " + this.height + "}";
  4121. };
  4122. /**
  4123. * Returns the string "Size"
  4124. */
  4125. Size.prototype.getClassName = function () {
  4126. return "Size";
  4127. };
  4128. /**
  4129. * Returns the Size hash code.
  4130. */
  4131. Size.prototype.getHashCode = function () {
  4132. var hash = this.width || 0;
  4133. hash = (hash * 397) ^ (this.height || 0);
  4134. return hash;
  4135. };
  4136. /**
  4137. * Updates the current size from the given one.
  4138. * Returns the updated Size.
  4139. */
  4140. Size.prototype.copyFrom = function (src) {
  4141. this.width = src.width;
  4142. this.height = src.height;
  4143. };
  4144. /**
  4145. * Updates in place the current Size from the given floats.
  4146. * Returns the updated Size.
  4147. */
  4148. Size.prototype.copyFromFloats = function (width, height) {
  4149. this.width = width;
  4150. this.height = height;
  4151. return this;
  4152. };
  4153. /**
  4154. * Updates in place the current Size from the given floats.
  4155. * Returns the updated Size.
  4156. */
  4157. Size.prototype.set = function (width, height) {
  4158. return this.copyFromFloats(width, height);
  4159. };
  4160. /**
  4161. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4162. */
  4163. Size.prototype.multiplyByFloats = function (w, h) {
  4164. return new Size(this.width * w, this.height * h);
  4165. };
  4166. /**
  4167. * Returns a new Size copied from the given one.
  4168. */
  4169. Size.prototype.clone = function () {
  4170. return new Size(this.width, this.height);
  4171. };
  4172. /**
  4173. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4174. */
  4175. Size.prototype.equals = function (other) {
  4176. if (!other) {
  4177. return false;
  4178. }
  4179. return (this.width === other.width) && (this.height === other.height);
  4180. };
  4181. Object.defineProperty(Size.prototype, "surface", {
  4182. /**
  4183. * Returns the surface of the Size : width * height (float).
  4184. */
  4185. get: function () {
  4186. return this.width * this.height;
  4187. },
  4188. enumerable: true,
  4189. configurable: true
  4190. });
  4191. /**
  4192. * Returns a new Size set to (0.0, 0.0)
  4193. */
  4194. Size.Zero = function () {
  4195. return new Size(0.0, 0.0);
  4196. };
  4197. /**
  4198. * Returns a new Size set as the addition result of the current Size and the given one.
  4199. */
  4200. Size.prototype.add = function (otherSize) {
  4201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4202. return r;
  4203. };
  4204. /**
  4205. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4206. */
  4207. Size.prototype.subtract = function (otherSize) {
  4208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4209. return r;
  4210. };
  4211. /**
  4212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4213. */
  4214. Size.Lerp = function (start, end, amount) {
  4215. var w = start.width + ((end.width - start.width) * amount);
  4216. var h = start.height + ((end.height - start.height) * amount);
  4217. return new Size(w, h);
  4218. };
  4219. return Size;
  4220. }());
  4221. BABYLON.Size = Size;
  4222. /**
  4223. * Class used to store quaternion data
  4224. * @see https://en.wikipedia.org/wiki/Quaternion
  4225. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4226. */
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the given floats
  4230. * @param x defines the first component (0 by default)
  4231. * @param y defines the second component (0 by default)
  4232. * @param z defines the third component (0 by default)
  4233. * @param w defines the fourth component (1.0 by default)
  4234. */
  4235. function Quaternion(
  4236. /** defines the first component (0 by default) */
  4237. x,
  4238. /** defines the second component (0 by default) */
  4239. y,
  4240. /** defines the third component (0 by default) */
  4241. z,
  4242. /** defines the fourth component (1.0 by default) */
  4243. w) {
  4244. if (x === void 0) { x = 0.0; }
  4245. if (y === void 0) { y = 0.0; }
  4246. if (z === void 0) { z = 0.0; }
  4247. if (w === void 0) { w = 1.0; }
  4248. this.x = x;
  4249. this.y = y;
  4250. this.z = z;
  4251. this.w = w;
  4252. }
  4253. /**
  4254. * Gets a string representation for the current quaternion
  4255. * @returns a string with the Quaternion coordinates
  4256. */
  4257. Quaternion.prototype.toString = function () {
  4258. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4259. };
  4260. /**
  4261. * Gets the class name of the quaternion
  4262. * @returns the string "Quaternion"
  4263. */
  4264. Quaternion.prototype.getClassName = function () {
  4265. return "Quaternion";
  4266. };
  4267. /**
  4268. * Gets a hash code for this quaternion
  4269. * @returns the quaternion hash code
  4270. */
  4271. Quaternion.prototype.getHashCode = function () {
  4272. var hash = this.x || 0;
  4273. hash = (hash * 397) ^ (this.y || 0);
  4274. hash = (hash * 397) ^ (this.z || 0);
  4275. hash = (hash * 397) ^ (this.w || 0);
  4276. return hash;
  4277. };
  4278. /**
  4279. * Copy the quaternion to an array
  4280. * @returns a new array populated with 4 elements from the quaternion coordinates
  4281. */
  4282. Quaternion.prototype.asArray = function () {
  4283. return [this.x, this.y, this.z, this.w];
  4284. };
  4285. /**
  4286. * Check if two quaternions are equals
  4287. * @param otherQuaternion defines the second operand
  4288. * @return true if the current quaternion and the given one coordinates are strictly equals
  4289. */
  4290. Quaternion.prototype.equals = function (otherQuaternion) {
  4291. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4292. };
  4293. /**
  4294. * Clone the current quaternion
  4295. * @returns a new quaternion copied from the current one
  4296. */
  4297. Quaternion.prototype.clone = function () {
  4298. return new Quaternion(this.x, this.y, this.z, this.w);
  4299. };
  4300. /**
  4301. * Copy a quaternion to the current one
  4302. * @param other defines the other quaternion
  4303. * @returns the updated current quaternion
  4304. */
  4305. Quaternion.prototype.copyFrom = function (other) {
  4306. this.x = other.x;
  4307. this.y = other.y;
  4308. this.z = other.z;
  4309. this.w = other.w;
  4310. return this;
  4311. };
  4312. /**
  4313. * Updates the current quaternion with the given float coordinates
  4314. * @param x defines the x coordinate
  4315. * @param y defines the y coordinate
  4316. * @param z defines the z coordinate
  4317. * @param w defines the w coordinate
  4318. * @returns the updated current quaternion
  4319. */
  4320. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4321. this.x = x;
  4322. this.y = y;
  4323. this.z = z;
  4324. this.w = w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current quaternion from the given float coordinates
  4329. * @param x defines the x coordinate
  4330. * @param y defines the y coordinate
  4331. * @param z defines the z coordinate
  4332. * @param w defines the w coordinate
  4333. * @returns the updated current quaternion
  4334. */
  4335. Quaternion.prototype.set = function (x, y, z, w) {
  4336. return this.copyFromFloats(x, y, z, w);
  4337. };
  4338. /**
  4339. * Adds two quaternions
  4340. * @param other defines the second operand
  4341. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4342. */
  4343. Quaternion.prototype.add = function (other) {
  4344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4345. };
  4346. /**
  4347. * Add a quaternion to the current one
  4348. * @param other defines the quaternion to add
  4349. * @returns the current quaternion
  4350. */
  4351. Quaternion.prototype.addInPlace = function (other) {
  4352. this.x += other.x;
  4353. this.y += other.y;
  4354. this.z += other.z;
  4355. this.w += other.w;
  4356. return this;
  4357. };
  4358. /**
  4359. * Subtract two quaternions
  4360. * @param other defines the second operand
  4361. * @returns a new quaternion as the subtraction result of the given one from the current one
  4362. */
  4363. Quaternion.prototype.subtract = function (other) {
  4364. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4365. };
  4366. /**
  4367. * Multiplies the current quaternion by a scale factor
  4368. * @param value defines the scale factor
  4369. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4370. */
  4371. Quaternion.prototype.scale = function (value) {
  4372. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4373. };
  4374. /**
  4375. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4376. * @param scale defines the scale factor
  4377. * @param result defines the Quaternion object where to store the result
  4378. * @returns the unmodified current quaternion
  4379. */
  4380. Quaternion.prototype.scaleToRef = function (scale, result) {
  4381. result.x = this.x * scale;
  4382. result.y = this.y * scale;
  4383. result.z = this.z * scale;
  4384. result.w = this.w * scale;
  4385. return this;
  4386. };
  4387. /**
  4388. * Multiplies in place the current quaternion by a scale factor
  4389. * @param value defines the scale factor
  4390. * @returns the current modified quaternion
  4391. */
  4392. Quaternion.prototype.scaleInPlace = function (value) {
  4393. this.x *= value;
  4394. this.y *= value;
  4395. this.z *= value;
  4396. this.w *= value;
  4397. return this;
  4398. };
  4399. /**
  4400. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4401. * @param scale defines the scale factor
  4402. * @param result defines the Quaternion object where to store the result
  4403. * @returns the unmodified current quaternion
  4404. */
  4405. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4406. result.x += this.x * scale;
  4407. result.y += this.y * scale;
  4408. result.z += this.z * scale;
  4409. result.w += this.w * scale;
  4410. return this;
  4411. };
  4412. /**
  4413. * Multiplies two quaternions
  4414. * @param q1 defines the second operand
  4415. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4416. */
  4417. Quaternion.prototype.multiply = function (q1) {
  4418. var result = new Quaternion(0, 0, 0, 1.0);
  4419. this.multiplyToRef(q1, result);
  4420. return result;
  4421. };
  4422. /**
  4423. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4424. * @param q1 defines the second operand
  4425. * @param result defines the target quaternion
  4426. * @returns the current quaternion
  4427. */
  4428. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4429. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4430. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4431. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4432. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4433. result.copyFromFloats(x, y, z, w);
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4438. * @param q1 defines the second operand
  4439. * @returns the currentupdated quaternion
  4440. */
  4441. Quaternion.prototype.multiplyInPlace = function (q1) {
  4442. this.multiplyToRef(q1, this);
  4443. return this;
  4444. };
  4445. /**
  4446. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4447. * @param ref defines the target quaternion
  4448. * @returns the current quaternion
  4449. */
  4450. Quaternion.prototype.conjugateToRef = function (ref) {
  4451. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4452. return this;
  4453. };
  4454. /**
  4455. * Conjugates in place (1-q) the current quaternion
  4456. * @returns the current updated quaternion
  4457. */
  4458. Quaternion.prototype.conjugateInPlace = function () {
  4459. this.x *= -1;
  4460. this.y *= -1;
  4461. this.z *= -1;
  4462. return this;
  4463. };
  4464. /**
  4465. * Conjugates in place (1-q) the current quaternion
  4466. * @returns a new quaternion
  4467. */
  4468. Quaternion.prototype.conjugate = function () {
  4469. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4470. return result;
  4471. };
  4472. /**
  4473. * Gets length of current quaternion
  4474. * @returns the quaternion length (float)
  4475. */
  4476. Quaternion.prototype.length = function () {
  4477. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4478. };
  4479. /**
  4480. * Normalize in place the current quaternion
  4481. * @returns the current updated quaternion
  4482. */
  4483. Quaternion.prototype.normalize = function () {
  4484. var length = 1.0 / this.length();
  4485. this.x *= length;
  4486. this.y *= length;
  4487. this.z *= length;
  4488. this.w *= length;
  4489. return this;
  4490. };
  4491. /**
  4492. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4493. * @param order is a reserved parameter and is ignore for now
  4494. * @returns a new Vector3 containing the Euler angles
  4495. */
  4496. Quaternion.prototype.toEulerAngles = function (order) {
  4497. if (order === void 0) { order = "YZX"; }
  4498. var result = Vector3.Zero();
  4499. this.toEulerAnglesToRef(result, order);
  4500. return result;
  4501. };
  4502. /**
  4503. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4504. * @param result defines the vector which will be filled with the Euler angles
  4505. * @param order is a reserved parameter and is ignore for now
  4506. * @returns the current unchanged quaternion
  4507. */
  4508. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4509. if (order === void 0) { order = "YZX"; }
  4510. var qz = this.z;
  4511. var qx = this.x;
  4512. var qy = this.y;
  4513. var qw = this.w;
  4514. var sqw = qw * qw;
  4515. var sqz = qz * qz;
  4516. var sqx = qx * qx;
  4517. var sqy = qy * qy;
  4518. var zAxisY = qy * qz - qx * qw;
  4519. var limit = .4999999;
  4520. if (zAxisY < -limit) {
  4521. result.y = 2 * Math.atan2(qy, qw);
  4522. result.x = Math.PI / 2;
  4523. result.z = 0;
  4524. }
  4525. else if (zAxisY > limit) {
  4526. result.y = 2 * Math.atan2(qy, qw);
  4527. result.x = -Math.PI / 2;
  4528. result.z = 0;
  4529. }
  4530. else {
  4531. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4532. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4533. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4534. }
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the given rotation matrix with the current quaternion values
  4539. * @param result defines the target matrix
  4540. * @returns the current unchanged quaternion
  4541. */
  4542. Quaternion.prototype.toRotationMatrix = function (result) {
  4543. var xx = this.x * this.x;
  4544. var yy = this.y * this.y;
  4545. var zz = this.z * this.z;
  4546. var xy = this.x * this.y;
  4547. var zw = this.z * this.w;
  4548. var zx = this.z * this.x;
  4549. var yw = this.y * this.w;
  4550. var yz = this.y * this.z;
  4551. var xw = this.x * this.w;
  4552. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4553. result.m[1] = 2.0 * (xy + zw);
  4554. result.m[2] = 2.0 * (zx - yw);
  4555. result.m[3] = 0;
  4556. result.m[4] = 2.0 * (xy - zw);
  4557. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4558. result.m[6] = 2.0 * (yz + xw);
  4559. result.m[7] = 0;
  4560. result.m[8] = 2.0 * (zx + yw);
  4561. result.m[9] = 2.0 * (yz - xw);
  4562. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4563. result.m[11] = 0;
  4564. result.m[12] = 0;
  4565. result.m[13] = 0;
  4566. result.m[14] = 0;
  4567. result.m[15] = 1.0;
  4568. result._markAsUpdated();
  4569. return this;
  4570. };
  4571. /**
  4572. * Updates the current quaternion from the given rotation matrix values
  4573. * @param matrix defines the source matrix
  4574. * @returns the current updated quaternion
  4575. */
  4576. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4577. Quaternion.FromRotationMatrixToRef(matrix, this);
  4578. return this;
  4579. };
  4580. // Statics
  4581. /**
  4582. * Creates a new quaternion from a rotation matrix
  4583. * @param matrix defines the source matrix
  4584. * @returns a new quaternion created from the given rotation matrix values
  4585. */
  4586. Quaternion.FromRotationMatrix = function (matrix) {
  4587. var result = new Quaternion();
  4588. Quaternion.FromRotationMatrixToRef(matrix, result);
  4589. return result;
  4590. };
  4591. /**
  4592. * Updates the given quaternion with the given rotation matrix values
  4593. * @param matrix defines the source matrix
  4594. * @param result defines the target quaternion
  4595. */
  4596. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4597. var data = matrix.m;
  4598. var m11 = data[0], m12 = data[4], m13 = data[8];
  4599. var m21 = data[1], m22 = data[5], m23 = data[9];
  4600. var m31 = data[2], m32 = data[6], m33 = data[10];
  4601. var trace = m11 + m22 + m33;
  4602. var s;
  4603. if (trace > 0) {
  4604. s = 0.5 / Math.sqrt(trace + 1.0);
  4605. result.w = 0.25 / s;
  4606. result.x = (m32 - m23) * s;
  4607. result.y = (m13 - m31) * s;
  4608. result.z = (m21 - m12) * s;
  4609. }
  4610. else if (m11 > m22 && m11 > m33) {
  4611. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4612. result.w = (m32 - m23) / s;
  4613. result.x = 0.25 * s;
  4614. result.y = (m12 + m21) / s;
  4615. result.z = (m13 + m31) / s;
  4616. }
  4617. else if (m22 > m33) {
  4618. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4619. result.w = (m13 - m31) / s;
  4620. result.x = (m12 + m21) / s;
  4621. result.y = 0.25 * s;
  4622. result.z = (m23 + m32) / s;
  4623. }
  4624. else {
  4625. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4626. result.w = (m21 - m12) / s;
  4627. result.x = (m13 + m31) / s;
  4628. result.y = (m23 + m32) / s;
  4629. result.z = 0.25 * s;
  4630. }
  4631. };
  4632. /**
  4633. * Creates an empty quaternion
  4634. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4635. */
  4636. Quaternion.Zero = function () {
  4637. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4638. };
  4639. /**
  4640. * Inverse a given quaternion
  4641. * @param q defines the source quaternion
  4642. * @returns a new quaternion as the inverted current quaternion
  4643. */
  4644. Quaternion.Inverse = function (q) {
  4645. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4646. };
  4647. /**
  4648. * Creates an identity quaternion
  4649. * @returns the identity quaternion
  4650. */
  4651. Quaternion.Identity = function () {
  4652. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4653. };
  4654. /**
  4655. * Gets a boolean indicating if the given quaternion is identity
  4656. * @param quaternion defines the quaternion to check
  4657. * @returns true if the quaternion is identity
  4658. */
  4659. Quaternion.IsIdentity = function (quaternion) {
  4660. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4661. };
  4662. /**
  4663. * Creates a quaternion from a rotation around an axis
  4664. * @param axis defines the axis to use
  4665. * @param angle defines the angle to use
  4666. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4667. */
  4668. Quaternion.RotationAxis = function (axis, angle) {
  4669. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4670. };
  4671. /**
  4672. * Creates a rotation around an axis and stores it into the given quaternion
  4673. * @param axis defines the axis to use
  4674. * @param angle defines the angle to use
  4675. * @param result defines the target quaternion
  4676. * @returns the target quaternion
  4677. */
  4678. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4679. var sin = Math.sin(angle / 2);
  4680. axis.normalize();
  4681. result.w = Math.cos(angle / 2);
  4682. result.x = axis.x * sin;
  4683. result.y = axis.y * sin;
  4684. result.z = axis.z * sin;
  4685. return result;
  4686. };
  4687. /**
  4688. * Creates a new quaternion from data stored into an array
  4689. * @param array defines the data source
  4690. * @param offset defines the offset in the source array where the data starts
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.FromArray = function (array, offset) {
  4694. if (!offset) {
  4695. offset = 0;
  4696. }
  4697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4698. };
  4699. /**
  4700. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4701. * @param yaw defines the rotation around Y axis
  4702. * @param pitch defines the rotation around X axis
  4703. * @param roll defines the rotation around Z axis
  4704. * @returns the new quaternion
  4705. */
  4706. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4707. var q = new Quaternion();
  4708. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4709. return q;
  4710. };
  4711. /**
  4712. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4713. * @param yaw defines the rotation around Y axis
  4714. * @param pitch defines the rotation around X axis
  4715. * @param roll defines the rotation around Z axis
  4716. * @param result defines the target quaternion
  4717. */
  4718. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4720. var halfRoll = roll * 0.5;
  4721. var halfPitch = pitch * 0.5;
  4722. var halfYaw = yaw * 0.5;
  4723. var sinRoll = Math.sin(halfRoll);
  4724. var cosRoll = Math.cos(halfRoll);
  4725. var sinPitch = Math.sin(halfPitch);
  4726. var cosPitch = Math.cos(halfPitch);
  4727. var sinYaw = Math.sin(halfYaw);
  4728. var cosYaw = Math.cos(halfYaw);
  4729. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4730. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4731. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4732. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4733. };
  4734. /**
  4735. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4736. * @param alpha defines the rotation around first axis
  4737. * @param beta defines the rotation around second axis
  4738. * @param gamma defines the rotation around third axis
  4739. * @returns the new quaternion
  4740. */
  4741. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4742. var result = new Quaternion();
  4743. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4748. * @param alpha defines the rotation around first axis
  4749. * @param beta defines the rotation around second axis
  4750. * @param gamma defines the rotation around third axis
  4751. * @param result defines the target quaternion
  4752. */
  4753. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4754. // Produces a quaternion from Euler angles in the z-x-z orientation
  4755. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4756. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4757. var halfBeta = beta * 0.5;
  4758. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4759. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4760. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4761. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4762. };
  4763. /**
  4764. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4765. * @param axis1 defines the first axis
  4766. * @param axis2 defines the second axis
  4767. * @param axis3 defines the third axis
  4768. * @returns the new quaternion
  4769. */
  4770. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4771. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4772. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4773. return quat;
  4774. };
  4775. /**
  4776. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4777. * @param axis1 defines the first axis
  4778. * @param axis2 defines the second axis
  4779. * @param axis3 defines the third axis
  4780. * @param ref defines the target quaternion
  4781. */
  4782. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4783. var rotMat = MathTmp.Matrix[0];
  4784. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4785. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4786. };
  4787. /**
  4788. * Interpolates between two quaternions
  4789. * @param left defines first quaternion
  4790. * @param right defines second quaternion
  4791. * @param amount defines the gradient to use
  4792. * @returns the new interpolated quaternion
  4793. */
  4794. Quaternion.Slerp = function (left, right, amount) {
  4795. var result = Quaternion.Identity();
  4796. Quaternion.SlerpToRef(left, right, amount, result);
  4797. return result;
  4798. };
  4799. /**
  4800. * Interpolates between two quaternions and stores it into a target quaternion
  4801. * @param left defines first quaternion
  4802. * @param right defines second quaternion
  4803. * @param amount defines the gradient to use
  4804. * @param result defines the target quaternion
  4805. */
  4806. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4807. var num2;
  4808. var num3;
  4809. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4810. var flag = false;
  4811. if (num4 < 0) {
  4812. flag = true;
  4813. num4 = -num4;
  4814. }
  4815. if (num4 > 0.999999) {
  4816. num3 = 1 - amount;
  4817. num2 = flag ? -amount : amount;
  4818. }
  4819. else {
  4820. var num5 = Math.acos(num4);
  4821. var num6 = (1.0 / Math.sin(num5));
  4822. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4823. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4824. }
  4825. result.x = (num3 * left.x) + (num2 * right.x);
  4826. result.y = (num3 * left.y) + (num2 * right.y);
  4827. result.z = (num3 * left.z) + (num2 * right.z);
  4828. result.w = (num3 * left.w) + (num2 * right.w);
  4829. };
  4830. /**
  4831. * Interpolate between two quaternions using Hermite interpolation
  4832. * @param value1 defines first quaternion
  4833. * @param tangent1 defines the incoming tangent
  4834. * @param value2 defines second quaternion
  4835. * @param tangent2 defines the outgoing tangent
  4836. * @param amount defines the target quaternion
  4837. * @returns the new interpolated quaternion
  4838. */
  4839. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4840. var squared = amount * amount;
  4841. var cubed = amount * squared;
  4842. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4843. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4844. var part3 = (cubed - (2.0 * squared)) + amount;
  4845. var part4 = cubed - squared;
  4846. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4847. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4848. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4849. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4850. return new Quaternion(x, y, z, w);
  4851. };
  4852. return Quaternion;
  4853. }());
  4854. BABYLON.Quaternion = Quaternion;
  4855. /**
  4856. * Class used to store matrix data (4x4)
  4857. */
  4858. var Matrix = /** @class */ (function () {
  4859. /**
  4860. * Creates an empty matrix (filled with zeros)
  4861. */
  4862. function Matrix() {
  4863. this._isIdentity = false;
  4864. this._isIdentityDirty = true;
  4865. /**
  4866. * Gets or sets the internal data of the matrix
  4867. */
  4868. this.m = new Float32Array(16);
  4869. this._markAsUpdated();
  4870. }
  4871. /** @ignore */
  4872. Matrix.prototype._markAsUpdated = function () {
  4873. this.updateFlag = Matrix._updateFlagSeed++;
  4874. this._isIdentityDirty = true;
  4875. };
  4876. // Properties
  4877. /**
  4878. * Check if the current matrix is indentity
  4879. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4880. * @returns true is the matrix is the identity matrix
  4881. */
  4882. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4883. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4884. if (this._isIdentityDirty) {
  4885. this._isIdentityDirty = false;
  4886. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4887. this._isIdentity = false;
  4888. }
  4889. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4890. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4891. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4892. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4893. this._isIdentity = false;
  4894. }
  4895. else {
  4896. this._isIdentity = true;
  4897. }
  4898. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4899. this._isIdentity = false;
  4900. }
  4901. }
  4902. return this._isIdentity;
  4903. };
  4904. /**
  4905. * Gets the determinant of the matrix
  4906. * @returns the matrix determinant
  4907. */
  4908. Matrix.prototype.determinant = function () {
  4909. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4910. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4911. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4912. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4913. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4914. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4915. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4916. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4917. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4918. };
  4919. // Methods
  4920. /**
  4921. * Returns the matrix as a Float32Array
  4922. * @returns the matrix underlying array
  4923. */
  4924. Matrix.prototype.toArray = function () {
  4925. return this.m;
  4926. };
  4927. /**
  4928. * Returns the matrix as a Float32Array
  4929. * @returns the matrix underlying array.
  4930. */
  4931. Matrix.prototype.asArray = function () {
  4932. return this.toArray();
  4933. };
  4934. /**
  4935. * Inverts the current matrix in place
  4936. * @returns the current inverted matrix
  4937. */
  4938. Matrix.prototype.invert = function () {
  4939. this.invertToRef(this);
  4940. return this;
  4941. };
  4942. /**
  4943. * Sets all the matrix elements to zero
  4944. * @returns the current matrix
  4945. */
  4946. Matrix.prototype.reset = function () {
  4947. for (var index = 0; index < 16; index++) {
  4948. this.m[index] = 0.0;
  4949. }
  4950. this._markAsUpdated();
  4951. return this;
  4952. };
  4953. /**
  4954. * Adds the current matrix with a second one
  4955. * @param other defines the matrix to add
  4956. * @returns a new matrix as the addition of the current matrix and the given one
  4957. */
  4958. Matrix.prototype.add = function (other) {
  4959. var result = new Matrix();
  4960. this.addToRef(other, result);
  4961. return result;
  4962. };
  4963. /**
  4964. * Sets the given matrix "result" to the addition of the current matrix and the given one
  4965. * @param other defines the matrix to add
  4966. * @param result defines the target matrix
  4967. * @returns the current matrix
  4968. */
  4969. Matrix.prototype.addToRef = function (other, result) {
  4970. for (var index = 0; index < 16; index++) {
  4971. result.m[index] = this.m[index] + other.m[index];
  4972. }
  4973. result._markAsUpdated();
  4974. return this;
  4975. };
  4976. /**
  4977. * Adds in place the given matrix to the current matrix
  4978. * @param other defines the second operand
  4979. * @returns the current updated matrix
  4980. */
  4981. Matrix.prototype.addToSelf = function (other) {
  4982. for (var index = 0; index < 16; index++) {
  4983. this.m[index] += other.m[index];
  4984. }
  4985. this._markAsUpdated();
  4986. return this;
  4987. };
  4988. /**
  4989. * Sets the given matrix to the current inverted Matrix
  4990. * @param other defines the target matrix
  4991. * @returns the unmodified current matrix
  4992. */
  4993. Matrix.prototype.invertToRef = function (other) {
  4994. var l1 = this.m[0];
  4995. var l2 = this.m[1];
  4996. var l3 = this.m[2];
  4997. var l4 = this.m[3];
  4998. var l5 = this.m[4];
  4999. var l6 = this.m[5];
  5000. var l7 = this.m[6];
  5001. var l8 = this.m[7];
  5002. var l9 = this.m[8];
  5003. var l10 = this.m[9];
  5004. var l11 = this.m[10];
  5005. var l12 = this.m[11];
  5006. var l13 = this.m[12];
  5007. var l14 = this.m[13];
  5008. var l15 = this.m[14];
  5009. var l16 = this.m[15];
  5010. var l17 = (l11 * l16) - (l12 * l15);
  5011. var l18 = (l10 * l16) - (l12 * l14);
  5012. var l19 = (l10 * l15) - (l11 * l14);
  5013. var l20 = (l9 * l16) - (l12 * l13);
  5014. var l21 = (l9 * l15) - (l11 * l13);
  5015. var l22 = (l9 * l14) - (l10 * l13);
  5016. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5017. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5018. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5019. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5020. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5021. var l28 = (l7 * l16) - (l8 * l15);
  5022. var l29 = (l6 * l16) - (l8 * l14);
  5023. var l30 = (l6 * l15) - (l7 * l14);
  5024. var l31 = (l5 * l16) - (l8 * l13);
  5025. var l32 = (l5 * l15) - (l7 * l13);
  5026. var l33 = (l5 * l14) - (l6 * l13);
  5027. var l34 = (l7 * l12) - (l8 * l11);
  5028. var l35 = (l6 * l12) - (l8 * l10);
  5029. var l36 = (l6 * l11) - (l7 * l10);
  5030. var l37 = (l5 * l12) - (l8 * l9);
  5031. var l38 = (l5 * l11) - (l7 * l9);
  5032. var l39 = (l5 * l10) - (l6 * l9);
  5033. other.m[0] = l23 * l27;
  5034. other.m[4] = l24 * l27;
  5035. other.m[8] = l25 * l27;
  5036. other.m[12] = l26 * l27;
  5037. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5038. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5039. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5040. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5041. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5042. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5043. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5044. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5045. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5046. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5047. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5048. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5049. other._markAsUpdated();
  5050. return this;
  5051. };
  5052. /**
  5053. * Inserts the translation vector (using 3 floats) in the current matrix
  5054. * @param x defines the 1st component of the translation
  5055. * @param y defines the 2nd component of the translation
  5056. * @param z defines the 3rd component of the translation
  5057. * @returns the current updated matrix
  5058. */
  5059. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5060. this.m[12] = x;
  5061. this.m[13] = y;
  5062. this.m[14] = z;
  5063. this._markAsUpdated();
  5064. return this;
  5065. };
  5066. /**
  5067. * Inserts the translation vector in the current matrix
  5068. * @param vector3 defines the translation to insert
  5069. * @returns the current updated matrix
  5070. */
  5071. Matrix.prototype.setTranslation = function (vector3) {
  5072. this.m[12] = vector3.x;
  5073. this.m[13] = vector3.y;
  5074. this.m[14] = vector3.z;
  5075. this._markAsUpdated();
  5076. return this;
  5077. };
  5078. /**
  5079. * Gets the translation value of the current matrix
  5080. * @returns a new Vector3 as the extracted translation from the matrix
  5081. */
  5082. Matrix.prototype.getTranslation = function () {
  5083. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5084. };
  5085. /**
  5086. * Fill a Vector3 with the extracted translation from the matrix
  5087. * @param result defines the Vector3 where to store the translation
  5088. * @returns the current matrix
  5089. */
  5090. Matrix.prototype.getTranslationToRef = function (result) {
  5091. result.x = this.m[12];
  5092. result.y = this.m[13];
  5093. result.z = this.m[14];
  5094. return this;
  5095. };
  5096. /**
  5097. * Remove rotation and scaling part from the matrix
  5098. * @returns the updated matrix
  5099. */
  5100. Matrix.prototype.removeRotationAndScaling = function () {
  5101. this.setRowFromFloats(0, 1, 0, 0, 0);
  5102. this.setRowFromFloats(1, 0, 1, 0, 0);
  5103. this.setRowFromFloats(2, 0, 0, 1, 0);
  5104. return this;
  5105. };
  5106. /**
  5107. * Multiply two matrices
  5108. * @param other defines the second operand
  5109. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5110. */
  5111. Matrix.prototype.multiply = function (other) {
  5112. var result = new Matrix();
  5113. this.multiplyToRef(other, result);
  5114. return result;
  5115. };
  5116. /**
  5117. * Copy the current matrix from the given one
  5118. * @param other defines the source matrix
  5119. * @returns the current updated matrix
  5120. */
  5121. Matrix.prototype.copyFrom = function (other) {
  5122. for (var index = 0; index < 16; index++) {
  5123. this.m[index] = other.m[index];
  5124. }
  5125. this._markAsUpdated();
  5126. return this;
  5127. };
  5128. /**
  5129. * Populates the given array from the starting index with the current matrix values
  5130. * @param array defines the target array
  5131. * @param offset defines the offset in the target array where to start storing values
  5132. * @returns the current matrix
  5133. */
  5134. Matrix.prototype.copyToArray = function (array, offset) {
  5135. if (offset === void 0) { offset = 0; }
  5136. for (var index = 0; index < 16; index++) {
  5137. array[offset + index] = this.m[index];
  5138. }
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5143. * @param other defines the second operand
  5144. * @param result defines the matrix where to store the multiplication
  5145. * @returns the current matrix
  5146. */
  5147. Matrix.prototype.multiplyToRef = function (other, result) {
  5148. this.multiplyToArray(other, result.m, 0);
  5149. result._markAsUpdated();
  5150. return this;
  5151. };
  5152. /**
  5153. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5154. * @param other defines the second operand
  5155. * @param result defines the array where to store the multiplication
  5156. * @param offset defines the offset in the target array where to start storing values
  5157. * @returns the current matrix
  5158. */
  5159. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5160. var tm0 = this.m[0];
  5161. var tm1 = this.m[1];
  5162. var tm2 = this.m[2];
  5163. var tm3 = this.m[3];
  5164. var tm4 = this.m[4];
  5165. var tm5 = this.m[5];
  5166. var tm6 = this.m[6];
  5167. var tm7 = this.m[7];
  5168. var tm8 = this.m[8];
  5169. var tm9 = this.m[9];
  5170. var tm10 = this.m[10];
  5171. var tm11 = this.m[11];
  5172. var tm12 = this.m[12];
  5173. var tm13 = this.m[13];
  5174. var tm14 = this.m[14];
  5175. var tm15 = this.m[15];
  5176. var om0 = other.m[0];
  5177. var om1 = other.m[1];
  5178. var om2 = other.m[2];
  5179. var om3 = other.m[3];
  5180. var om4 = other.m[4];
  5181. var om5 = other.m[5];
  5182. var om6 = other.m[6];
  5183. var om7 = other.m[7];
  5184. var om8 = other.m[8];
  5185. var om9 = other.m[9];
  5186. var om10 = other.m[10];
  5187. var om11 = other.m[11];
  5188. var om12 = other.m[12];
  5189. var om13 = other.m[13];
  5190. var om14 = other.m[14];
  5191. var om15 = other.m[15];
  5192. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5193. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5194. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5195. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5196. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5197. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5198. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5199. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5200. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5201. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5202. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5203. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5204. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5205. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5206. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5207. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5208. return this;
  5209. };
  5210. /**
  5211. * Check equality between this matrix and a second one
  5212. * @param value defines the second matrix to compare
  5213. * @returns true is the current matrix and the given one values are strictly equal
  5214. */
  5215. Matrix.prototype.equals = function (value) {
  5216. return value &&
  5217. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5218. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5219. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5220. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5221. };
  5222. /**
  5223. * Clone the current matrix
  5224. * @returns a new matrix from the current matrix
  5225. */
  5226. Matrix.prototype.clone = function () {
  5227. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5228. };
  5229. /**
  5230. * Returns the name of the current matrix class
  5231. * @returns the string "Matrix"
  5232. */
  5233. Matrix.prototype.getClassName = function () {
  5234. return "Matrix";
  5235. };
  5236. /**
  5237. * Gets the hash code of the current matrix
  5238. * @returns the hash code
  5239. */
  5240. Matrix.prototype.getHashCode = function () {
  5241. var hash = this.m[0] || 0;
  5242. for (var i = 1; i < 16; i++) {
  5243. hash = (hash * 397) ^ (this.m[i] || 0);
  5244. }
  5245. return hash;
  5246. };
  5247. /**
  5248. * Decomposes the current Matrix into a translation, rotation and scaling components
  5249. * @param scale defines the scale vector3 given as a reference to update
  5250. * @param rotation defines the rotation quaternion given as a reference to update
  5251. * @param translation defines the translation vector3 given as a reference to update
  5252. * @returns true if operation was successful
  5253. */
  5254. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5255. if (translation) {
  5256. translation.x = this.m[12];
  5257. translation.y = this.m[13];
  5258. translation.z = this.m[14];
  5259. }
  5260. scale = scale || MathTmp.Vector3[0];
  5261. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5262. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5263. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5264. if (this.determinant() <= 0) {
  5265. scale.y *= -1;
  5266. }
  5267. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5268. if (rotation) {
  5269. rotation.x = 0;
  5270. rotation.y = 0;
  5271. rotation.z = 0;
  5272. rotation.w = 1;
  5273. }
  5274. return false;
  5275. }
  5276. if (rotation) {
  5277. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5278. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5279. }
  5280. return true;
  5281. };
  5282. /**
  5283. * Gets specific row of the matrix
  5284. * @param index defines the number of the row to get
  5285. * @returns the index-th row of the current matrix as a new Vector4
  5286. */
  5287. Matrix.prototype.getRow = function (index) {
  5288. if (index < 0 || index > 3) {
  5289. return null;
  5290. }
  5291. var i = index * 4;
  5292. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5293. };
  5294. /**
  5295. * Sets the index-th row of the current matrix to the vector4 values
  5296. * @param index defines the number of the row to set
  5297. * @param row defines the target vector4
  5298. * @returns the updated current matrix
  5299. */
  5300. Matrix.prototype.setRow = function (index, row) {
  5301. if (index < 0 || index > 3) {
  5302. return this;
  5303. }
  5304. var i = index * 4;
  5305. this.m[i + 0] = row.x;
  5306. this.m[i + 1] = row.y;
  5307. this.m[i + 2] = row.z;
  5308. this.m[i + 3] = row.w;
  5309. this._markAsUpdated();
  5310. return this;
  5311. };
  5312. /**
  5313. * Compute the transpose of the matrix
  5314. * @returns the new transposed matrix
  5315. */
  5316. Matrix.prototype.transpose = function () {
  5317. return Matrix.Transpose(this);
  5318. };
  5319. /**
  5320. * Compute the transpose of the matrix and store it in a given matrix
  5321. * @param result defines the target matrix
  5322. * @returns the current matrix
  5323. */
  5324. Matrix.prototype.transposeToRef = function (result) {
  5325. Matrix.TransposeToRef(this, result);
  5326. return this;
  5327. };
  5328. /**
  5329. * Sets the index-th row of the current matrix with the given 4 x float values
  5330. * @param index defines the row index
  5331. * @param x defines the x component to set
  5332. * @param y defines the y component to set
  5333. * @param z defines the z component to set
  5334. * @param w defines the w component to set
  5335. * @returns the updated current matrix
  5336. */
  5337. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5338. if (index < 0 || index > 3) {
  5339. return this;
  5340. }
  5341. var i = index * 4;
  5342. this.m[i + 0] = x;
  5343. this.m[i + 1] = y;
  5344. this.m[i + 2] = z;
  5345. this.m[i + 3] = w;
  5346. this._markAsUpdated();
  5347. return this;
  5348. };
  5349. /**
  5350. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5351. * @param scale defines the scale factor
  5352. * @returns a new matrix
  5353. */
  5354. Matrix.prototype.scale = function (scale) {
  5355. var result = new Matrix();
  5356. this.scaleToRef(scale, result);
  5357. return result;
  5358. };
  5359. /**
  5360. * Scale the current matrix values by a factor to a given result matrix
  5361. * @param scale defines the scale factor
  5362. * @param result defines the matrix to store the result
  5363. * @returns the current matrix
  5364. */
  5365. Matrix.prototype.scaleToRef = function (scale, result) {
  5366. for (var index = 0; index < 16; index++) {
  5367. result.m[index] = this.m[index] * scale;
  5368. }
  5369. result._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Scale the current matrix values by a factor and add the result to a given matrix
  5374. * @param scale defines the scale factor
  5375. * @param result defines the Matrix to store the result
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5379. for (var index = 0; index < 16; index++) {
  5380. result.m[index] += this.m[index] * scale;
  5381. }
  5382. result._markAsUpdated();
  5383. return this;
  5384. };
  5385. /**
  5386. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5387. * @param ref matrix to store the result
  5388. */
  5389. Matrix.prototype.toNormalMatrix = function (ref) {
  5390. this.invertToRef(ref);
  5391. ref.transpose();
  5392. var m = ref.m;
  5393. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5394. };
  5395. /**
  5396. * Gets only rotation part of the current matrix
  5397. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5398. */
  5399. Matrix.prototype.getRotationMatrix = function () {
  5400. var result = Matrix.Identity();
  5401. this.getRotationMatrixToRef(result);
  5402. return result;
  5403. };
  5404. /**
  5405. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5406. * @param result defines the target matrix to store data to
  5407. * @returns the current matrix
  5408. */
  5409. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5410. var m = this.m;
  5411. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5412. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5413. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5414. if (this.determinant() <= 0) {
  5415. sy *= -1;
  5416. }
  5417. if (sx === 0 || sy === 0 || sz === 0) {
  5418. Matrix.IdentityToRef(result);
  5419. }
  5420. else {
  5421. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5422. }
  5423. return this;
  5424. };
  5425. // Statics
  5426. /**
  5427. * Creates a matrix from an array
  5428. * @param array defines the source array
  5429. * @param offset defines an offset in the source array
  5430. * @returns a new Matrix set from the starting index of the given array
  5431. */
  5432. Matrix.FromArray = function (array, offset) {
  5433. var result = new Matrix();
  5434. if (!offset) {
  5435. offset = 0;
  5436. }
  5437. Matrix.FromArrayToRef(array, offset, result);
  5438. return result;
  5439. };
  5440. /**
  5441. * Copy the content of an array into a given matrix
  5442. * @param array defines the source array
  5443. * @param offset defines an offset in the source array
  5444. * @param result defines the target matrix
  5445. */
  5446. Matrix.FromArrayToRef = function (array, offset, result) {
  5447. for (var index = 0; index < 16; index++) {
  5448. result.m[index] = array[index + offset];
  5449. }
  5450. result._markAsUpdated();
  5451. };
  5452. /**
  5453. * Stores an array into a matrix after having multiplied each component by a given factor
  5454. * @param array defines the source array
  5455. * @param offset defines the offset in the source array
  5456. * @param scale defines the scaling factor
  5457. * @param result defines the target matrix
  5458. */
  5459. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5460. for (var index = 0; index < 16; index++) {
  5461. result.m[index] = array[index + offset] * scale;
  5462. }
  5463. result._markAsUpdated();
  5464. };
  5465. /**
  5466. * Stores a list of values (16) inside a given matrix
  5467. * @param initialM11 defines 1st value of 1st row
  5468. * @param initialM12 defines 2nd value of 1st row
  5469. * @param initialM13 defines 3rd value of 1st row
  5470. * @param initialM14 defines 4th value of 1st row
  5471. * @param initialM21 defines 1st value of 2nd row
  5472. * @param initialM22 defines 2nd value of 2nd row
  5473. * @param initialM23 defines 3rd value of 2nd row
  5474. * @param initialM24 defines 4th value of 2nd row
  5475. * @param initialM31 defines 1st value of 3rd row
  5476. * @param initialM32 defines 2nd value of 3rd row
  5477. * @param initialM33 defines 3rd value of 3rd row
  5478. * @param initialM34 defines 4th value of 3rd row
  5479. * @param initialM41 defines 1st value of 4th row
  5480. * @param initialM42 defines 2nd value of 4th row
  5481. * @param initialM43 defines 3rd value of 4th row
  5482. * @param initialM44 defines 4th value of 4th row
  5483. * @param result defines the target matrix
  5484. */
  5485. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5486. result.m[0] = initialM11;
  5487. result.m[1] = initialM12;
  5488. result.m[2] = initialM13;
  5489. result.m[3] = initialM14;
  5490. result.m[4] = initialM21;
  5491. result.m[5] = initialM22;
  5492. result.m[6] = initialM23;
  5493. result.m[7] = initialM24;
  5494. result.m[8] = initialM31;
  5495. result.m[9] = initialM32;
  5496. result.m[10] = initialM33;
  5497. result.m[11] = initialM34;
  5498. result.m[12] = initialM41;
  5499. result.m[13] = initialM42;
  5500. result.m[14] = initialM43;
  5501. result.m[15] = initialM44;
  5502. result._markAsUpdated();
  5503. };
  5504. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5505. /**
  5506. * Gets an identity matrix that must not be updated
  5507. */
  5508. get: function () {
  5509. return Matrix._identityReadOnly;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. /**
  5515. * Creates new matrix from a list of values (16)
  5516. * @param initialM11 defines 1st value of 1st row
  5517. * @param initialM12 defines 2nd value of 1st row
  5518. * @param initialM13 defines 3rd value of 1st row
  5519. * @param initialM14 defines 4th value of 1st row
  5520. * @param initialM21 defines 1st value of 2nd row
  5521. * @param initialM22 defines 2nd value of 2nd row
  5522. * @param initialM23 defines 3rd value of 2nd row
  5523. * @param initialM24 defines 4th value of 2nd row
  5524. * @param initialM31 defines 1st value of 3rd row
  5525. * @param initialM32 defines 2nd value of 3rd row
  5526. * @param initialM33 defines 3rd value of 3rd row
  5527. * @param initialM34 defines 4th value of 3rd row
  5528. * @param initialM41 defines 1st value of 4th row
  5529. * @param initialM42 defines 2nd value of 4th row
  5530. * @param initialM43 defines 3rd value of 4th row
  5531. * @param initialM44 defines 4th value of 4th row
  5532. * @returns the new matrix
  5533. */
  5534. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5535. var result = new Matrix();
  5536. result.m[0] = initialM11;
  5537. result.m[1] = initialM12;
  5538. result.m[2] = initialM13;
  5539. result.m[3] = initialM14;
  5540. result.m[4] = initialM21;
  5541. result.m[5] = initialM22;
  5542. result.m[6] = initialM23;
  5543. result.m[7] = initialM24;
  5544. result.m[8] = initialM31;
  5545. result.m[9] = initialM32;
  5546. result.m[10] = initialM33;
  5547. result.m[11] = initialM34;
  5548. result.m[12] = initialM41;
  5549. result.m[13] = initialM42;
  5550. result.m[14] = initialM43;
  5551. result.m[15] = initialM44;
  5552. return result;
  5553. };
  5554. /**
  5555. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5556. * @param scale defines the scale vector3
  5557. * @param rotation defines the rotation quaternion
  5558. * @param translation defines the translation vector3
  5559. * @returns a new matrix
  5560. */
  5561. Matrix.Compose = function (scale, rotation, translation) {
  5562. var result = Matrix.Identity();
  5563. Matrix.ComposeToRef(scale, rotation, translation, result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5568. * @param scale defines the scale vector3
  5569. * @param rotation defines the rotation quaternion
  5570. * @param translation defines the translation vector3
  5571. * @param result defines the target matrix
  5572. */
  5573. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5574. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5575. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5576. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5577. result.setTranslation(translation);
  5578. };
  5579. /**
  5580. * Creates a new identity matrix
  5581. * @returns a new identity matrix
  5582. */
  5583. Matrix.Identity = function () {
  5584. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5585. };
  5586. /**
  5587. * Creates a new identity matrix and stores the result in a given matrix
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.IdentityToRef = function (result) {
  5591. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5592. };
  5593. /**
  5594. * Creates a new zero matrix
  5595. * @returns a new zero matrix
  5596. */
  5597. Matrix.Zero = function () {
  5598. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5599. };
  5600. /**
  5601. * Creates a new rotation matrix for "angle" radians around the X axis
  5602. * @param angle defines the angle (in radians) to use
  5603. * @return the new matrix
  5604. */
  5605. Matrix.RotationX = function (angle) {
  5606. var result = new Matrix();
  5607. Matrix.RotationXToRef(angle, result);
  5608. return result;
  5609. };
  5610. /**
  5611. * Creates a new matrix as the invert of a given matrix
  5612. * @param source defines the source matrix
  5613. * @returns the new matrix
  5614. */
  5615. Matrix.Invert = function (source) {
  5616. var result = new Matrix();
  5617. source.invertToRef(result);
  5618. return result;
  5619. };
  5620. /**
  5621. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5622. * @param angle defines the angle (in radians) to use
  5623. * @param result defines the target matrix
  5624. */
  5625. Matrix.RotationXToRef = function (angle, result) {
  5626. var s = Math.sin(angle);
  5627. var c = Math.cos(angle);
  5628. result.m[0] = 1.0;
  5629. result.m[15] = 1.0;
  5630. result.m[5] = c;
  5631. result.m[10] = c;
  5632. result.m[9] = -s;
  5633. result.m[6] = s;
  5634. result.m[1] = 0.0;
  5635. result.m[2] = 0.0;
  5636. result.m[3] = 0.0;
  5637. result.m[4] = 0.0;
  5638. result.m[7] = 0.0;
  5639. result.m[8] = 0.0;
  5640. result.m[11] = 0.0;
  5641. result.m[12] = 0.0;
  5642. result.m[13] = 0.0;
  5643. result.m[14] = 0.0;
  5644. result._markAsUpdated();
  5645. };
  5646. /**
  5647. * Creates a new rotation matrix for "angle" radians around the Y axis
  5648. * @param angle defines the angle (in radians) to use
  5649. * @return the new matrix
  5650. */
  5651. Matrix.RotationY = function (angle) {
  5652. var result = new Matrix();
  5653. Matrix.RotationYToRef(angle, result);
  5654. return result;
  5655. };
  5656. /**
  5657. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5658. * @param angle defines the angle (in radians) to use
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.RotationYToRef = function (angle, result) {
  5662. var s = Math.sin(angle);
  5663. var c = Math.cos(angle);
  5664. result.m[5] = 1.0;
  5665. result.m[15] = 1.0;
  5666. result.m[0] = c;
  5667. result.m[2] = -s;
  5668. result.m[8] = s;
  5669. result.m[10] = c;
  5670. result.m[1] = 0.0;
  5671. result.m[3] = 0.0;
  5672. result.m[4] = 0.0;
  5673. result.m[6] = 0.0;
  5674. result.m[7] = 0.0;
  5675. result.m[9] = 0.0;
  5676. result.m[11] = 0.0;
  5677. result.m[12] = 0.0;
  5678. result.m[13] = 0.0;
  5679. result.m[14] = 0.0;
  5680. result._markAsUpdated();
  5681. };
  5682. /**
  5683. * Creates a new rotation matrix for "angle" radians around the Z axis
  5684. * @param angle defines the angle (in radians) to use
  5685. * @return the new matrix
  5686. */
  5687. Matrix.RotationZ = function (angle) {
  5688. var result = new Matrix();
  5689. Matrix.RotationZToRef(angle, result);
  5690. return result;
  5691. };
  5692. /**
  5693. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5694. * @param angle defines the angle (in radians) to use
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.RotationZToRef = function (angle, result) {
  5698. var s = Math.sin(angle);
  5699. var c = Math.cos(angle);
  5700. result.m[10] = 1.0;
  5701. result.m[15] = 1.0;
  5702. result.m[0] = c;
  5703. result.m[1] = s;
  5704. result.m[4] = -s;
  5705. result.m[5] = c;
  5706. result.m[2] = 0.0;
  5707. result.m[3] = 0.0;
  5708. result.m[6] = 0.0;
  5709. result.m[7] = 0.0;
  5710. result.m[8] = 0.0;
  5711. result.m[9] = 0.0;
  5712. result.m[11] = 0.0;
  5713. result.m[12] = 0.0;
  5714. result.m[13] = 0.0;
  5715. result.m[14] = 0.0;
  5716. result._markAsUpdated();
  5717. };
  5718. /**
  5719. * Creates a new rotation matrix for "angle" radians around the given axis
  5720. * @param axis defines the axis to use
  5721. * @param angle defines the angle (in radians) to use
  5722. * @return the new matrix
  5723. */
  5724. Matrix.RotationAxis = function (axis, angle) {
  5725. var result = Matrix.Zero();
  5726. Matrix.RotationAxisToRef(axis, angle, result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5731. * @param axis defines the axis to use
  5732. * @param angle defines the angle (in radians) to use
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5736. var s = Math.sin(-angle);
  5737. var c = Math.cos(-angle);
  5738. var c1 = 1 - c;
  5739. axis.normalize();
  5740. result.m[0] = (axis.x * axis.x) * c1 + c;
  5741. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5742. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5743. result.m[3] = 0.0;
  5744. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5745. result.m[5] = (axis.y * axis.y) * c1 + c;
  5746. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5747. result.m[7] = 0.0;
  5748. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5749. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5750. result.m[10] = (axis.z * axis.z) * c1 + c;
  5751. result.m[11] = 0.0;
  5752. result.m[15] = 1.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a rotation matrix
  5757. * @param yaw defines the yaw angle in radians (Y axis)
  5758. * @param pitch defines the pitch angle in radians (X axis)
  5759. * @param roll defines the roll angle in radians (X axis)
  5760. * @returns the new rotation matrix
  5761. */
  5762. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5763. var result = new Matrix();
  5764. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a rotation matrix and stores it in a given matrix
  5769. * @param yaw defines the yaw angle in radians (Y axis)
  5770. * @param pitch defines the pitch angle in radians (X axis)
  5771. * @param roll defines the roll angle in radians (X axis)
  5772. * @param result defines the target matrix
  5773. */
  5774. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5775. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5776. this._tempQuaternion.toRotationMatrix(result);
  5777. };
  5778. /**
  5779. * Creates a scaling matrix
  5780. * @param x defines the scale factor on X axis
  5781. * @param y defines the scale factor on Y axis
  5782. * @param z defines the scale factor on Z axis
  5783. * @returns the new matrix
  5784. */
  5785. Matrix.Scaling = function (x, y, z) {
  5786. var result = Matrix.Zero();
  5787. Matrix.ScalingToRef(x, y, z, result);
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a scaling matrix and stores it in a given matrix
  5792. * @param x defines the scale factor on X axis
  5793. * @param y defines the scale factor on Y axis
  5794. * @param z defines the scale factor on Z axis
  5795. * @param result defines the target matrix
  5796. */
  5797. Matrix.ScalingToRef = function (x, y, z, result) {
  5798. result.m[0] = x;
  5799. result.m[1] = 0.0;
  5800. result.m[2] = 0.0;
  5801. result.m[3] = 0.0;
  5802. result.m[4] = 0.0;
  5803. result.m[5] = y;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[8] = 0.0;
  5807. result.m[9] = 0.0;
  5808. result.m[10] = z;
  5809. result.m[11] = 0.0;
  5810. result.m[12] = 0.0;
  5811. result.m[13] = 0.0;
  5812. result.m[14] = 0.0;
  5813. result.m[15] = 1.0;
  5814. result._markAsUpdated();
  5815. };
  5816. /**
  5817. * Creates a translation matrix
  5818. * @param x defines the translation on X axis
  5819. * @param y defines the translation on Y axis
  5820. * @param z defines the translationon Z axis
  5821. * @returns the new matrix
  5822. */
  5823. Matrix.Translation = function (x, y, z) {
  5824. var result = Matrix.Identity();
  5825. Matrix.TranslationToRef(x, y, z, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a translation matrix and stores it in a given matrix
  5830. * @param x defines the translation on X axis
  5831. * @param y defines the translation on Y axis
  5832. * @param z defines the translationon Z axis
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.TranslationToRef = function (x, y, z, result) {
  5836. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5837. };
  5838. /**
  5839. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5840. * @param startValue defines the start value
  5841. * @param endValue defines the end value
  5842. * @param gradient defines the gradient factor
  5843. * @returns the new matrix
  5844. */
  5845. Matrix.Lerp = function (startValue, endValue, gradient) {
  5846. var result = Matrix.Zero();
  5847. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5852. * @param startValue defines the start value
  5853. * @param endValue defines the end value
  5854. * @param gradient defines the gradient factor
  5855. * @param result defines the Matrix object where to store data
  5856. */
  5857. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5858. for (var index = 0; index < 16; index++) {
  5859. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5860. }
  5861. result._markAsUpdated();
  5862. };
  5863. /**
  5864. * Builds a new matrix whose values are computed by:
  5865. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5866. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5867. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5868. * @param startValue defines the first matrix
  5869. * @param endValue defines the second matrix
  5870. * @param gradient defines the gradient between the two matrices
  5871. * @returns the new matrix
  5872. */
  5873. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5874. var result = Matrix.Zero();
  5875. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Update a matrix to values which are computed by:
  5880. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5881. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5882. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5883. * @param startValue defines the first matrix
  5884. * @param endValue defines the second matrix
  5885. * @param gradient defines the gradient between the two matrices
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5889. var startScale = MathTmp.Vector3[0];
  5890. var startRotation = MathTmp.Quaternion[0];
  5891. var startTranslation = MathTmp.Vector3[1];
  5892. startValue.decompose(startScale, startRotation, startTranslation);
  5893. var endScale = MathTmp.Vector3[2];
  5894. var endRotation = MathTmp.Quaternion[1];
  5895. var endTranslation = MathTmp.Vector3[3];
  5896. endValue.decompose(endScale, endRotation, endTranslation);
  5897. var resultScale = MathTmp.Vector3[4];
  5898. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5899. var resultRotation = MathTmp.Quaternion[2];
  5900. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5901. var resultTranslation = MathTmp.Vector3[5];
  5902. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5903. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5904. };
  5905. /**
  5906. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5907. * This function works in left handed mode
  5908. * @param eye defines the final position of the entity
  5909. * @param target defines where the entity should look at
  5910. * @param up defines the up vector for the entity
  5911. * @returns the new matrix
  5912. */
  5913. Matrix.LookAtLH = function (eye, target, up) {
  5914. var result = Matrix.Zero();
  5915. Matrix.LookAtLHToRef(eye, target, up, result);
  5916. return result;
  5917. };
  5918. /**
  5919. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5920. * This function works in left handed mode
  5921. * @param eye defines the final position of the entity
  5922. * @param target defines where the entity should look at
  5923. * @param up defines the up vector for the entity
  5924. * @param result defines the target matrix
  5925. */
  5926. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5927. // Z axis
  5928. target.subtractToRef(eye, this._zAxis);
  5929. this._zAxis.normalize();
  5930. // X axis
  5931. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5932. if (this._xAxis.lengthSquared() === 0) {
  5933. this._xAxis.x = 1.0;
  5934. }
  5935. else {
  5936. this._xAxis.normalize();
  5937. }
  5938. // Y axis
  5939. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5940. this._yAxis.normalize();
  5941. // Eye angles
  5942. var ex = -Vector3.Dot(this._xAxis, eye);
  5943. var ey = -Vector3.Dot(this._yAxis, eye);
  5944. var ez = -Vector3.Dot(this._zAxis, eye);
  5945. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5946. };
  5947. /**
  5948. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5949. * This function works in right handed mode
  5950. * @param eye defines the final position of the entity
  5951. * @param target defines where the entity should look at
  5952. * @param up defines the up vector for the entity
  5953. * @returns the new matrix
  5954. */
  5955. Matrix.LookAtRH = function (eye, target, up) {
  5956. var result = Matrix.Zero();
  5957. Matrix.LookAtRHToRef(eye, target, up, result);
  5958. return result;
  5959. };
  5960. /**
  5961. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5962. * This function works in right handed mode
  5963. * @param eye defines the final position of the entity
  5964. * @param target defines where the entity should look at
  5965. * @param up defines the up vector for the entity
  5966. * @param result defines the target matrix
  5967. */
  5968. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5969. // Z axis
  5970. eye.subtractToRef(target, this._zAxis);
  5971. this._zAxis.normalize();
  5972. // X axis
  5973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5974. if (this._xAxis.lengthSquared() === 0) {
  5975. this._xAxis.x = 1.0;
  5976. }
  5977. else {
  5978. this._xAxis.normalize();
  5979. }
  5980. // Y axis
  5981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5982. this._yAxis.normalize();
  5983. // Eye angles
  5984. var ex = -Vector3.Dot(this._xAxis, eye);
  5985. var ey = -Vector3.Dot(this._yAxis, eye);
  5986. var ez = -Vector3.Dot(this._zAxis, eye);
  5987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5988. };
  5989. /**
  5990. * Create a left-handed orthographic projection matrix
  5991. * @param width defines the viewport width
  5992. * @param height defines the viewport height
  5993. * @param znear defines the near clip plane
  5994. * @param zfar defines the far clip plane
  5995. * @returns a new matrix as a left-handed orthographic projection matrix
  5996. */
  5997. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5998. var matrix = Matrix.Zero();
  5999. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6000. return matrix;
  6001. };
  6002. /**
  6003. * Store a left-handed orthographic projection to a given matrix
  6004. * @param width defines the viewport width
  6005. * @param height defines the viewport height
  6006. * @param znear defines the near clip plane
  6007. * @param zfar defines the far clip plane
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6011. var n = znear;
  6012. var f = zfar;
  6013. var a = 2.0 / width;
  6014. var b = 2.0 / height;
  6015. var c = 2.0 / (f - n);
  6016. var d = -(f + n) / (f - n);
  6017. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6018. };
  6019. /**
  6020. * Create a left-handed orthographic projection matrix
  6021. * @param left defines the viewport left coordinate
  6022. * @param right defines the viewport right coordinate
  6023. * @param bottom defines the viewport bottom coordinate
  6024. * @param top defines the viewport top coordinate
  6025. * @param znear defines the near clip plane
  6026. * @param zfar defines the far clip plane
  6027. * @returns a new matrix as a left-handed orthographic projection matrix
  6028. */
  6029. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6030. var matrix = Matrix.Zero();
  6031. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6032. return matrix;
  6033. };
  6034. /**
  6035. * Stores a left-handed orthographic projection into a given matrix
  6036. * @param left defines the viewport left coordinate
  6037. * @param right defines the viewport right coordinate
  6038. * @param bottom defines the viewport bottom coordinate
  6039. * @param top defines the viewport top coordinate
  6040. * @param znear defines the near clip plane
  6041. * @param zfar defines the far clip plane
  6042. * @param result defines the target matrix
  6043. */
  6044. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6045. var n = znear;
  6046. var f = zfar;
  6047. var a = 2.0 / (right - left);
  6048. var b = 2.0 / (top - bottom);
  6049. var c = 2.0 / (f - n);
  6050. var d = -(f + n) / (f - n);
  6051. var i0 = (left + right) / (left - right);
  6052. var i1 = (top + bottom) / (bottom - top);
  6053. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6054. };
  6055. /**
  6056. * Creates a right-handed orthographic projection matrix
  6057. * @param left defines the viewport left coordinate
  6058. * @param right defines the viewport right coordinate
  6059. * @param bottom defines the viewport bottom coordinate
  6060. * @param top defines the viewport top coordinate
  6061. * @param znear defines the near clip plane
  6062. * @param zfar defines the far clip plane
  6063. * @returns a new matrix as a right-handed orthographic projection matrix
  6064. */
  6065. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6066. var matrix = Matrix.Zero();
  6067. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6068. return matrix;
  6069. };
  6070. /**
  6071. * Stores a right-handed orthographic projection into a given matrix
  6072. * @param left defines the viewport left coordinate
  6073. * @param right defines the viewport right coordinate
  6074. * @param bottom defines the viewport bottom coordinate
  6075. * @param top defines the viewport top coordinate
  6076. * @param znear defines the near clip plane
  6077. * @param zfar defines the far clip plane
  6078. * @param result defines the target matrix
  6079. */
  6080. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6081. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6082. result.m[10] *= -1.0;
  6083. };
  6084. /**
  6085. * Creates a left-handed perspective projection matrix
  6086. * @param width defines the viewport width
  6087. * @param height defines the viewport height
  6088. * @param znear defines the near clip plane
  6089. * @param zfar defines the far clip plane
  6090. * @returns a new matrix as a left-handed perspective projection matrix
  6091. */
  6092. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6093. var matrix = Matrix.Zero();
  6094. var n = znear;
  6095. var f = zfar;
  6096. var a = 2.0 * n / width;
  6097. var b = 2.0 * n / height;
  6098. var c = (f + n) / (f - n);
  6099. var d = -2.0 * f * n / (f - n);
  6100. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6101. return matrix;
  6102. };
  6103. /**
  6104. * Creates a left-handed perspective projection matrix
  6105. * @param fov defines the horizontal field of view
  6106. * @param aspect defines the aspect ratio
  6107. * @param znear defines the near clip plane
  6108. * @param zfar defines the far clip plane
  6109. * @returns a new matrix as a left-handed perspective projection matrix
  6110. */
  6111. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6112. var matrix = Matrix.Zero();
  6113. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6114. return matrix;
  6115. };
  6116. /**
  6117. * Stores a left-handed perspective projection into a given matrix
  6118. * @param fov defines the horizontal field of view
  6119. * @param aspect defines the aspect ratio
  6120. * @param znear defines the near clip plane
  6121. * @param zfar defines the far clip plane
  6122. * @param result defines the target matrix
  6123. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6124. */
  6125. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6126. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6127. var n = znear;
  6128. var f = zfar;
  6129. var t = 1.0 / (Math.tan(fov * 0.5));
  6130. var a = isVerticalFovFixed ? (t / aspect) : t;
  6131. var b = isVerticalFovFixed ? t : (t * aspect);
  6132. var c = (f + n) / (f - n);
  6133. var d = -2.0 * f * n / (f - n);
  6134. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6135. };
  6136. /**
  6137. * Creates a right-handed perspective projection matrix
  6138. * @param fov defines the horizontal field of view
  6139. * @param aspect defines the aspect ratio
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a right-handed perspective projection matrix
  6143. */
  6144. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Stores a right-handed perspective projection into a given matrix
  6151. * @param fov defines the horizontal field of view
  6152. * @param aspect defines the aspect ratio
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6157. */
  6158. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6159. //alternatively this could be expressed as:
  6160. // m = PerspectiveFovLHToRef
  6161. // m[10] *= -1.0;
  6162. // m[11] *= -1.0;
  6163. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6164. var n = znear;
  6165. var f = zfar;
  6166. var t = 1.0 / (Math.tan(fov * 0.5));
  6167. var a = isVerticalFovFixed ? (t / aspect) : t;
  6168. var b = isVerticalFovFixed ? t : (t * aspect);
  6169. var c = -(f + n) / (f - n);
  6170. var d = -2 * f * n / (f - n);
  6171. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6172. };
  6173. /**
  6174. * Stores a perspective projection for WebVR info a given matrix
  6175. * @param fov defines the field of view
  6176. * @param znear defines the near clip plane
  6177. * @param zfar defines the far clip plane
  6178. * @param result defines the target matrix
  6179. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6180. */
  6181. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6182. if (rightHanded === void 0) { rightHanded = false; }
  6183. var rightHandedFactor = rightHanded ? -1 : 1;
  6184. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6185. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6186. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6187. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6188. var xScale = 2.0 / (leftTan + rightTan);
  6189. var yScale = 2.0 / (upTan + downTan);
  6190. result.m[0] = xScale;
  6191. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6192. result.m[5] = yScale;
  6193. result.m[6] = result.m[7] = 0.0;
  6194. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6195. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6196. result.m[10] = -zfar / (znear - zfar);
  6197. result.m[11] = 1.0 * rightHandedFactor;
  6198. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6199. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6200. result._markAsUpdated();
  6201. };
  6202. /**
  6203. * Computes a complete transformation matrix
  6204. * @param viewport defines the viewport to use
  6205. * @param world defines the world matrix
  6206. * @param view defines the view matrix
  6207. * @param projection defines the projection matrix
  6208. * @param zmin defines the near clip plane
  6209. * @param zmax defines the far clip plane
  6210. * @returns the transformation matrix
  6211. */
  6212. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6213. var cw = viewport.width;
  6214. var ch = viewport.height;
  6215. var cx = viewport.x;
  6216. var cy = viewport.y;
  6217. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6218. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6219. };
  6220. /**
  6221. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6222. * @param matrix defines the matrix to use
  6223. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6224. */
  6225. Matrix.GetAsMatrix2x2 = function (matrix) {
  6226. return new Float32Array([
  6227. matrix.m[0], matrix.m[1],
  6228. matrix.m[4], matrix.m[5]
  6229. ]);
  6230. };
  6231. /**
  6232. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6233. * @param matrix defines the matrix to use
  6234. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6235. */
  6236. Matrix.GetAsMatrix3x3 = function (matrix) {
  6237. return new Float32Array([
  6238. matrix.m[0], matrix.m[1], matrix.m[2],
  6239. matrix.m[4], matrix.m[5], matrix.m[6],
  6240. matrix.m[8], matrix.m[9], matrix.m[10]
  6241. ]);
  6242. };
  6243. /**
  6244. * Compute the transpose of a given matrix
  6245. * @param matrix defines the matrix to transpose
  6246. * @returns the new matrix
  6247. */
  6248. Matrix.Transpose = function (matrix) {
  6249. var result = new Matrix();
  6250. Matrix.TransposeToRef(matrix, result);
  6251. return result;
  6252. };
  6253. /**
  6254. * Compute the transpose of a matrix and store it in a target matrix
  6255. * @param matrix defines the matrix to transpose
  6256. * @param result defines the target matrix
  6257. */
  6258. Matrix.TransposeToRef = function (matrix, result) {
  6259. result.m[0] = matrix.m[0];
  6260. result.m[1] = matrix.m[4];
  6261. result.m[2] = matrix.m[8];
  6262. result.m[3] = matrix.m[12];
  6263. result.m[4] = matrix.m[1];
  6264. result.m[5] = matrix.m[5];
  6265. result.m[6] = matrix.m[9];
  6266. result.m[7] = matrix.m[13];
  6267. result.m[8] = matrix.m[2];
  6268. result.m[9] = matrix.m[6];
  6269. result.m[10] = matrix.m[10];
  6270. result.m[11] = matrix.m[14];
  6271. result.m[12] = matrix.m[3];
  6272. result.m[13] = matrix.m[7];
  6273. result.m[14] = matrix.m[11];
  6274. result.m[15] = matrix.m[15];
  6275. };
  6276. /**
  6277. * Computes a reflection matrix from a plane
  6278. * @param plane defines the reflection plane
  6279. * @returns a new matrix
  6280. */
  6281. Matrix.Reflection = function (plane) {
  6282. var matrix = new Matrix();
  6283. Matrix.ReflectionToRef(plane, matrix);
  6284. return matrix;
  6285. };
  6286. /**
  6287. * Computes a reflection matrix from a plane
  6288. * @param plane defines the reflection plane
  6289. * @param result defines the target matrix
  6290. */
  6291. Matrix.ReflectionToRef = function (plane, result) {
  6292. plane.normalize();
  6293. var x = plane.normal.x;
  6294. var y = plane.normal.y;
  6295. var z = plane.normal.z;
  6296. var temp = -2 * x;
  6297. var temp2 = -2 * y;
  6298. var temp3 = -2 * z;
  6299. result.m[0] = (temp * x) + 1;
  6300. result.m[1] = temp2 * x;
  6301. result.m[2] = temp3 * x;
  6302. result.m[3] = 0.0;
  6303. result.m[4] = temp * y;
  6304. result.m[5] = (temp2 * y) + 1;
  6305. result.m[6] = temp3 * y;
  6306. result.m[7] = 0.0;
  6307. result.m[8] = temp * z;
  6308. result.m[9] = temp2 * z;
  6309. result.m[10] = (temp3 * z) + 1;
  6310. result.m[11] = 0.0;
  6311. result.m[12] = temp * plane.d;
  6312. result.m[13] = temp2 * plane.d;
  6313. result.m[14] = temp3 * plane.d;
  6314. result.m[15] = 1.0;
  6315. result._markAsUpdated();
  6316. };
  6317. /**
  6318. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6319. * @param xaxis defines the value of the 1st axis
  6320. * @param yaxis defines the value of the 2nd axis
  6321. * @param zaxis defines the value of the 3rd axis
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6325. result.m[0] = xaxis.x;
  6326. result.m[1] = xaxis.y;
  6327. result.m[2] = xaxis.z;
  6328. result.m[3] = 0.0;
  6329. result.m[4] = yaxis.x;
  6330. result.m[5] = yaxis.y;
  6331. result.m[6] = yaxis.z;
  6332. result.m[7] = 0.0;
  6333. result.m[8] = zaxis.x;
  6334. result.m[9] = zaxis.y;
  6335. result.m[10] = zaxis.z;
  6336. result.m[11] = 0.0;
  6337. result.m[12] = 0.0;
  6338. result.m[13] = 0.0;
  6339. result.m[14] = 0.0;
  6340. result.m[15] = 1.0;
  6341. result._markAsUpdated();
  6342. };
  6343. /**
  6344. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6345. * @param quat defines the quaternion to use
  6346. * @param result defines the target matrix
  6347. */
  6348. Matrix.FromQuaternionToRef = function (quat, result) {
  6349. var xx = quat.x * quat.x;
  6350. var yy = quat.y * quat.y;
  6351. var zz = quat.z * quat.z;
  6352. var xy = quat.x * quat.y;
  6353. var zw = quat.z * quat.w;
  6354. var zx = quat.z * quat.x;
  6355. var yw = quat.y * quat.w;
  6356. var yz = quat.y * quat.z;
  6357. var xw = quat.x * quat.w;
  6358. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6359. result.m[1] = 2.0 * (xy + zw);
  6360. result.m[2] = 2.0 * (zx - yw);
  6361. result.m[3] = 0.0;
  6362. result.m[4] = 2.0 * (xy - zw);
  6363. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6364. result.m[6] = 2.0 * (yz + xw);
  6365. result.m[7] = 0.0;
  6366. result.m[8] = 2.0 * (zx + yw);
  6367. result.m[9] = 2.0 * (yz - xw);
  6368. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6369. result.m[11] = 0.0;
  6370. result.m[12] = 0.0;
  6371. result.m[13] = 0.0;
  6372. result.m[14] = 0.0;
  6373. result.m[15] = 1.0;
  6374. result._markAsUpdated();
  6375. };
  6376. Matrix._tempQuaternion = new Quaternion();
  6377. Matrix._xAxis = Vector3.Zero();
  6378. Matrix._yAxis = Vector3.Zero();
  6379. Matrix._zAxis = Vector3.Zero();
  6380. Matrix._updateFlagSeed = 0;
  6381. Matrix._identityReadOnly = Matrix.Identity();
  6382. return Matrix;
  6383. }());
  6384. BABYLON.Matrix = Matrix;
  6385. var Plane = /** @class */ (function () {
  6386. /**
  6387. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6388. */
  6389. function Plane(a, b, c, d) {
  6390. this.normal = new Vector3(a, b, c);
  6391. this.d = d;
  6392. }
  6393. /**
  6394. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6395. */
  6396. Plane.prototype.asArray = function () {
  6397. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6398. };
  6399. // Methods
  6400. /**
  6401. * Returns a new plane copied from the current Plane.
  6402. */
  6403. Plane.prototype.clone = function () {
  6404. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6405. };
  6406. /**
  6407. * Returns the string "Plane".
  6408. */
  6409. Plane.prototype.getClassName = function () {
  6410. return "Plane";
  6411. };
  6412. /**
  6413. * Returns the Plane hash code.
  6414. */
  6415. Plane.prototype.getHashCode = function () {
  6416. var hash = this.normal.getHashCode();
  6417. hash = (hash * 397) ^ (this.d || 0);
  6418. return hash;
  6419. };
  6420. /**
  6421. * Normalize the current Plane in place.
  6422. * Returns the updated Plane.
  6423. */
  6424. Plane.prototype.normalize = function () {
  6425. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6426. var magnitude = 0.0;
  6427. if (norm !== 0) {
  6428. magnitude = 1.0 / norm;
  6429. }
  6430. this.normal.x *= magnitude;
  6431. this.normal.y *= magnitude;
  6432. this.normal.z *= magnitude;
  6433. this.d *= magnitude;
  6434. return this;
  6435. };
  6436. /**
  6437. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6438. */
  6439. Plane.prototype.transform = function (transformation) {
  6440. var transposedMatrix = Matrix.Transpose(transformation);
  6441. var x = this.normal.x;
  6442. var y = this.normal.y;
  6443. var z = this.normal.z;
  6444. var d = this.d;
  6445. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6446. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6447. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6448. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6449. return new Plane(normalX, normalY, normalZ, finalD);
  6450. };
  6451. /**
  6452. * Returns the dot product (float) of the point coordinates and the plane normal.
  6453. */
  6454. Plane.prototype.dotCoordinate = function (point) {
  6455. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6456. };
  6457. /**
  6458. * Updates the current Plane from the plane defined by the three given points.
  6459. * Returns the updated Plane.
  6460. */
  6461. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6462. var x1 = point2.x - point1.x;
  6463. var y1 = point2.y - point1.y;
  6464. var z1 = point2.z - point1.z;
  6465. var x2 = point3.x - point1.x;
  6466. var y2 = point3.y - point1.y;
  6467. var z2 = point3.z - point1.z;
  6468. var yz = (y1 * z2) - (z1 * y2);
  6469. var xz = (z1 * x2) - (x1 * z2);
  6470. var xy = (x1 * y2) - (y1 * x2);
  6471. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6472. var invPyth;
  6473. if (pyth !== 0) {
  6474. invPyth = 1.0 / pyth;
  6475. }
  6476. else {
  6477. invPyth = 0.0;
  6478. }
  6479. this.normal.x = yz * invPyth;
  6480. this.normal.y = xz * invPyth;
  6481. this.normal.z = xy * invPyth;
  6482. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6483. return this;
  6484. };
  6485. /**
  6486. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6487. */
  6488. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6489. var dot = Vector3.Dot(this.normal, direction);
  6490. return (dot <= epsilon);
  6491. };
  6492. /**
  6493. * Returns the signed distance (float) from the given point to the Plane.
  6494. */
  6495. Plane.prototype.signedDistanceTo = function (point) {
  6496. return Vector3.Dot(point, this.normal) + this.d;
  6497. };
  6498. // Statics
  6499. /**
  6500. * Returns a new Plane from the given array.
  6501. */
  6502. Plane.FromArray = function (array) {
  6503. return new Plane(array[0], array[1], array[2], array[3]);
  6504. };
  6505. /**
  6506. * Returns a new Plane defined by the three given points.
  6507. */
  6508. Plane.FromPoints = function (point1, point2, point3) {
  6509. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6510. result.copyFromPoints(point1, point2, point3);
  6511. return result;
  6512. };
  6513. /**
  6514. * Returns a new Plane the normal vector to this plane at the given origin point.
  6515. * Note : the vector "normal" is updated because normalized.
  6516. */
  6517. Plane.FromPositionAndNormal = function (origin, normal) {
  6518. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6519. normal.normalize();
  6520. result.normal = normal;
  6521. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6522. return result;
  6523. };
  6524. /**
  6525. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6526. */
  6527. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6528. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6529. return Vector3.Dot(point, normal) + d;
  6530. };
  6531. return Plane;
  6532. }());
  6533. BABYLON.Plane = Plane;
  6534. var Viewport = /** @class */ (function () {
  6535. /**
  6536. * Creates a Viewport object located at (x, y) and sized (width, height).
  6537. */
  6538. function Viewport(x, y, width, height) {
  6539. this.x = x;
  6540. this.y = y;
  6541. this.width = width;
  6542. this.height = height;
  6543. }
  6544. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6545. if (renderWidthOrEngine.getRenderWidth) {
  6546. var engine = renderWidthOrEngine;
  6547. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6548. }
  6549. var renderWidth = renderWidthOrEngine;
  6550. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6551. };
  6552. /**
  6553. * Returns a new Viewport copied from the current one.
  6554. */
  6555. Viewport.prototype.clone = function () {
  6556. return new Viewport(this.x, this.y, this.width, this.height);
  6557. };
  6558. return Viewport;
  6559. }());
  6560. BABYLON.Viewport = Viewport;
  6561. var Frustum = /** @class */ (function () {
  6562. function Frustum() {
  6563. }
  6564. /**
  6565. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6566. */
  6567. Frustum.GetPlanes = function (transform) {
  6568. var frustumPlanes = [];
  6569. for (var index = 0; index < 6; index++) {
  6570. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6571. }
  6572. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6573. return frustumPlanes;
  6574. };
  6575. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6576. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6577. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6578. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6579. frustumPlane.d = transform.m[15] + transform.m[14];
  6580. frustumPlane.normalize();
  6581. };
  6582. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6583. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6584. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6585. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6586. frustumPlane.d = transform.m[15] - transform.m[14];
  6587. frustumPlane.normalize();
  6588. };
  6589. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6590. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6591. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6592. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6593. frustumPlane.d = transform.m[15] + transform.m[12];
  6594. frustumPlane.normalize();
  6595. };
  6596. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6597. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6598. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6599. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6600. frustumPlane.d = transform.m[15] - transform.m[12];
  6601. frustumPlane.normalize();
  6602. };
  6603. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6604. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6605. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6606. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6607. frustumPlane.d = transform.m[15] - transform.m[13];
  6608. frustumPlane.normalize();
  6609. };
  6610. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6611. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6612. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6613. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6614. frustumPlane.d = transform.m[15] + transform.m[13];
  6615. frustumPlane.normalize();
  6616. };
  6617. /**
  6618. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6619. */
  6620. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6621. // Near
  6622. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6623. // Far
  6624. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6625. // Left
  6626. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6627. // Right
  6628. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6629. // Top
  6630. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6631. // Bottom
  6632. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6633. };
  6634. return Frustum;
  6635. }());
  6636. BABYLON.Frustum = Frustum;
  6637. /** Defines supported spaces */
  6638. var Space;
  6639. (function (Space) {
  6640. /** Local (object) space */
  6641. Space[Space["LOCAL"] = 0] = "LOCAL";
  6642. /** World space */
  6643. Space[Space["WORLD"] = 1] = "WORLD";
  6644. /** Bone space */
  6645. Space[Space["BONE"] = 2] = "BONE";
  6646. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6647. /** Defines the 3 main axes */
  6648. var Axis = /** @class */ (function () {
  6649. function Axis() {
  6650. }
  6651. /** X axis */
  6652. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6653. /** Y axis */
  6654. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6655. /** Z axis */
  6656. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6657. return Axis;
  6658. }());
  6659. BABYLON.Axis = Axis;
  6660. ;
  6661. var BezierCurve = /** @class */ (function () {
  6662. function BezierCurve() {
  6663. }
  6664. /**
  6665. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6666. */
  6667. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6668. // Extract X (which is equal to time here)
  6669. var f0 = 1 - 3 * x2 + 3 * x1;
  6670. var f1 = 3 * x2 - 6 * x1;
  6671. var f2 = 3 * x1;
  6672. var refinedT = t;
  6673. for (var i = 0; i < 5; i++) {
  6674. var refinedT2 = refinedT * refinedT;
  6675. var refinedT3 = refinedT2 * refinedT;
  6676. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6677. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6678. refinedT -= (x - t) * slope;
  6679. refinedT = Math.min(1, Math.max(0, refinedT));
  6680. }
  6681. // Resolve cubic bezier for the given x
  6682. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6683. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6684. Math.pow(refinedT, 3);
  6685. };
  6686. return BezierCurve;
  6687. }());
  6688. BABYLON.BezierCurve = BezierCurve;
  6689. /**
  6690. * Defines potential orientation for back face culling
  6691. */
  6692. var Orientation;
  6693. (function (Orientation) {
  6694. /**
  6695. * Clockwise
  6696. */
  6697. Orientation[Orientation["CW"] = 0] = "CW";
  6698. /** Counter clockwise */
  6699. Orientation[Orientation["CCW"] = 1] = "CCW";
  6700. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6701. var Angle = /** @class */ (function () {
  6702. /**
  6703. * Creates an Angle object of "radians" radians (float).
  6704. */
  6705. function Angle(radians) {
  6706. var _this = this;
  6707. /**
  6708. * Returns the Angle value in degrees (float).
  6709. */
  6710. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6711. /**
  6712. * Returns the Angle value in radians (float).
  6713. */
  6714. this.radians = function () { return _this._radians; };
  6715. this._radians = radians;
  6716. if (this._radians < 0.0)
  6717. this._radians += (2.0 * Math.PI);
  6718. }
  6719. /**
  6720. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6721. */
  6722. Angle.BetweenTwoPoints = function (a, b) {
  6723. var delta = b.subtract(a);
  6724. var theta = Math.atan2(delta.y, delta.x);
  6725. return new Angle(theta);
  6726. };
  6727. /**
  6728. * Returns a new Angle object from the given float in radians.
  6729. */
  6730. Angle.FromRadians = function (radians) {
  6731. return new Angle(radians);
  6732. };
  6733. /**
  6734. * Returns a new Angle object from the given float in degrees.
  6735. */
  6736. Angle.FromDegrees = function (degrees) {
  6737. return new Angle(degrees * Math.PI / 180.0);
  6738. };
  6739. return Angle;
  6740. }());
  6741. BABYLON.Angle = Angle;
  6742. var Arc2 = /** @class */ (function () {
  6743. /**
  6744. * Creates an Arc object from the three given points : start, middle and end.
  6745. */
  6746. function Arc2(startPoint, midPoint, endPoint) {
  6747. this.startPoint = startPoint;
  6748. this.midPoint = midPoint;
  6749. this.endPoint = endPoint;
  6750. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6751. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6752. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6753. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6754. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6755. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6756. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6757. var a1 = this.startAngle.degrees();
  6758. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6759. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6760. // angles correction
  6761. if (a2 - a1 > +180.0)
  6762. a2 -= 360.0;
  6763. if (a2 - a1 < -180.0)
  6764. a2 += 360.0;
  6765. if (a3 - a2 > +180.0)
  6766. a3 -= 360.0;
  6767. if (a3 - a2 < -180.0)
  6768. a3 += 360.0;
  6769. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6770. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6771. }
  6772. return Arc2;
  6773. }());
  6774. BABYLON.Arc2 = Arc2;
  6775. var Path2 = /** @class */ (function () {
  6776. /**
  6777. * Creates a Path2 object from the starting 2D coordinates x and y.
  6778. */
  6779. function Path2(x, y) {
  6780. this._points = new Array();
  6781. this._length = 0.0;
  6782. this.closed = false;
  6783. this._points.push(new Vector2(x, y));
  6784. }
  6785. /**
  6786. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6787. * Returns the updated Path2.
  6788. */
  6789. Path2.prototype.addLineTo = function (x, y) {
  6790. if (this.closed) {
  6791. return this;
  6792. }
  6793. var newPoint = new Vector2(x, y);
  6794. var previousPoint = this._points[this._points.length - 1];
  6795. this._points.push(newPoint);
  6796. this._length += newPoint.subtract(previousPoint).length();
  6797. return this;
  6798. };
  6799. /**
  6800. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6801. * Returns the updated Path2.
  6802. */
  6803. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6804. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6805. if (this.closed) {
  6806. return this;
  6807. }
  6808. var startPoint = this._points[this._points.length - 1];
  6809. var midPoint = new Vector2(midX, midY);
  6810. var endPoint = new Vector2(endX, endY);
  6811. var arc = new Arc2(startPoint, midPoint, endPoint);
  6812. var increment = arc.angle.radians() / numberOfSegments;
  6813. if (arc.orientation === Orientation.CW)
  6814. increment *= -1;
  6815. var currentAngle = arc.startAngle.radians() + increment;
  6816. for (var i = 0; i < numberOfSegments; i++) {
  6817. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6818. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6819. this.addLineTo(x, y);
  6820. currentAngle += increment;
  6821. }
  6822. return this;
  6823. };
  6824. /**
  6825. * Closes the Path2.
  6826. * Returns the Path2.
  6827. */
  6828. Path2.prototype.close = function () {
  6829. this.closed = true;
  6830. return this;
  6831. };
  6832. /**
  6833. * Returns the Path2 total length (float).
  6834. */
  6835. Path2.prototype.length = function () {
  6836. var result = this._length;
  6837. if (!this.closed) {
  6838. var lastPoint = this._points[this._points.length - 1];
  6839. var firstPoint = this._points[0];
  6840. result += (firstPoint.subtract(lastPoint).length());
  6841. }
  6842. return result;
  6843. };
  6844. /**
  6845. * Returns the Path2 internal array of points.
  6846. */
  6847. Path2.prototype.getPoints = function () {
  6848. return this._points;
  6849. };
  6850. /**
  6851. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6852. */
  6853. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6854. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6855. return Vector2.Zero();
  6856. }
  6857. var lengthPosition = normalizedLengthPosition * this.length();
  6858. var previousOffset = 0;
  6859. for (var i = 0; i < this._points.length; i++) {
  6860. var j = (i + 1) % this._points.length;
  6861. var a = this._points[i];
  6862. var b = this._points[j];
  6863. var bToA = b.subtract(a);
  6864. var nextOffset = (bToA.length() + previousOffset);
  6865. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6866. var dir = bToA.normalize();
  6867. var localOffset = lengthPosition - previousOffset;
  6868. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6869. }
  6870. previousOffset = nextOffset;
  6871. }
  6872. return Vector2.Zero();
  6873. };
  6874. /**
  6875. * Returns a new Path2 starting at the coordinates (x, y).
  6876. */
  6877. Path2.StartingAt = function (x, y) {
  6878. return new Path2(x, y);
  6879. };
  6880. return Path2;
  6881. }());
  6882. BABYLON.Path2 = Path2;
  6883. var Path3D = /** @class */ (function () {
  6884. /**
  6885. * new Path3D(path, normal, raw)
  6886. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6887. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6888. * path : an array of Vector3, the curve axis of the Path3D
  6889. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6890. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6891. */
  6892. function Path3D(path, firstNormal, raw) {
  6893. if (firstNormal === void 0) { firstNormal = null; }
  6894. this.path = path;
  6895. this._curve = new Array();
  6896. this._distances = new Array();
  6897. this._tangents = new Array();
  6898. this._normals = new Array();
  6899. this._binormals = new Array();
  6900. for (var p = 0; p < path.length; p++) {
  6901. this._curve[p] = path[p].clone(); // hard copy
  6902. }
  6903. this._raw = raw || false;
  6904. this._compute(firstNormal);
  6905. }
  6906. /**
  6907. * Returns the Path3D array of successive Vector3 designing its curve.
  6908. */
  6909. Path3D.prototype.getCurve = function () {
  6910. return this._curve;
  6911. };
  6912. /**
  6913. * Returns an array populated with tangent vectors on each Path3D curve point.
  6914. */
  6915. Path3D.prototype.getTangents = function () {
  6916. return this._tangents;
  6917. };
  6918. /**
  6919. * Returns an array populated with normal vectors on each Path3D curve point.
  6920. */
  6921. Path3D.prototype.getNormals = function () {
  6922. return this._normals;
  6923. };
  6924. /**
  6925. * Returns an array populated with binormal vectors on each Path3D curve point.
  6926. */
  6927. Path3D.prototype.getBinormals = function () {
  6928. return this._binormals;
  6929. };
  6930. /**
  6931. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6932. */
  6933. Path3D.prototype.getDistances = function () {
  6934. return this._distances;
  6935. };
  6936. /**
  6937. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6938. * Returns the same object updated.
  6939. */
  6940. Path3D.prototype.update = function (path, firstNormal) {
  6941. if (firstNormal === void 0) { firstNormal = null; }
  6942. for (var p = 0; p < path.length; p++) {
  6943. this._curve[p].x = path[p].x;
  6944. this._curve[p].y = path[p].y;
  6945. this._curve[p].z = path[p].z;
  6946. }
  6947. this._compute(firstNormal);
  6948. return this;
  6949. };
  6950. // private function compute() : computes tangents, normals and binormals
  6951. Path3D.prototype._compute = function (firstNormal) {
  6952. var l = this._curve.length;
  6953. // first and last tangents
  6954. this._tangents[0] = this._getFirstNonNullVector(0);
  6955. if (!this._raw) {
  6956. this._tangents[0].normalize();
  6957. }
  6958. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6959. if (!this._raw) {
  6960. this._tangents[l - 1].normalize();
  6961. }
  6962. // normals and binormals at first point : arbitrary vector with _normalVector()
  6963. var tg0 = this._tangents[0];
  6964. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6965. this._normals[0] = pp0;
  6966. if (!this._raw) {
  6967. this._normals[0].normalize();
  6968. }
  6969. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6970. if (!this._raw) {
  6971. this._binormals[0].normalize();
  6972. }
  6973. this._distances[0] = 0.0;
  6974. // normals and binormals : next points
  6975. var prev; // previous vector (segment)
  6976. var cur; // current vector (segment)
  6977. var curTang; // current tangent
  6978. // previous normal
  6979. var prevBinor; // previous binormal
  6980. for (var i = 1; i < l; i++) {
  6981. // tangents
  6982. prev = this._getLastNonNullVector(i);
  6983. if (i < l - 1) {
  6984. cur = this._getFirstNonNullVector(i);
  6985. this._tangents[i] = prev.add(cur);
  6986. this._tangents[i].normalize();
  6987. }
  6988. this._distances[i] = this._distances[i - 1] + prev.length();
  6989. // normals and binormals
  6990. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6991. curTang = this._tangents[i];
  6992. prevBinor = this._binormals[i - 1];
  6993. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6994. if (!this._raw) {
  6995. this._normals[i].normalize();
  6996. }
  6997. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6998. if (!this._raw) {
  6999. this._binormals[i].normalize();
  7000. }
  7001. }
  7002. };
  7003. // private function getFirstNonNullVector(index)
  7004. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7005. Path3D.prototype._getFirstNonNullVector = function (index) {
  7006. var i = 1;
  7007. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7008. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7009. i++;
  7010. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7011. }
  7012. return nNVector;
  7013. };
  7014. // private function getLastNonNullVector(index)
  7015. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7016. Path3D.prototype._getLastNonNullVector = function (index) {
  7017. var i = 1;
  7018. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7019. while (nLVector.length() === 0 && index > i + 1) {
  7020. i++;
  7021. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7022. }
  7023. return nLVector;
  7024. };
  7025. // private function normalVector(v0, vt, va) :
  7026. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7027. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7028. Path3D.prototype._normalVector = function (v0, vt, va) {
  7029. var normal0;
  7030. var tgl = vt.length();
  7031. if (tgl === 0.0) {
  7032. tgl = 1.0;
  7033. }
  7034. if (va === undefined || va === null) {
  7035. var point;
  7036. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7037. point = new Vector3(0.0, -1.0, 0.0);
  7038. }
  7039. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7040. point = new Vector3(1.0, 0.0, 0.0);
  7041. }
  7042. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7043. point = new Vector3(0.0, 0.0, 1.0);
  7044. }
  7045. else {
  7046. point = Vector3.Zero();
  7047. }
  7048. normal0 = Vector3.Cross(vt, point);
  7049. }
  7050. else {
  7051. normal0 = Vector3.Cross(vt, va);
  7052. Vector3.CrossToRef(normal0, vt, normal0);
  7053. }
  7054. normal0.normalize();
  7055. return normal0;
  7056. };
  7057. return Path3D;
  7058. }());
  7059. BABYLON.Path3D = Path3D;
  7060. var Curve3 = /** @class */ (function () {
  7061. /**
  7062. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7063. * A Curve3 is designed from a series of successive Vector3.
  7064. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7065. */
  7066. function Curve3(points) {
  7067. this._length = 0.0;
  7068. this._points = points;
  7069. this._length = this._computeLength(points);
  7070. }
  7071. /**
  7072. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7073. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7074. * @param v1 (Vector3) the control point
  7075. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7076. * @param nbPoints (integer) the wanted number of points in the curve
  7077. */
  7078. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7079. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7080. var bez = new Array();
  7081. var equation = function (t, val0, val1, val2) {
  7082. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7083. return res;
  7084. };
  7085. for (var i = 0; i <= nbPoints; i++) {
  7086. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7087. }
  7088. return new Curve3(bez);
  7089. };
  7090. /**
  7091. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7092. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7093. * @param v1 (Vector3) the first control point
  7094. * @param v2 (Vector3) the second control point
  7095. * @param v3 (Vector3) the end point of the Cubic Bezier
  7096. * @param nbPoints (integer) the wanted number of points in the curve
  7097. */
  7098. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7099. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7100. var bez = new Array();
  7101. var equation = function (t, val0, val1, val2, val3) {
  7102. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7103. return res;
  7104. };
  7105. for (var i = 0; i <= nbPoints; i++) {
  7106. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7107. }
  7108. return new Curve3(bez);
  7109. };
  7110. /**
  7111. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7112. * @param p1 (Vector3) the origin point of the Hermite Spline
  7113. * @param t1 (Vector3) the tangent vector at the origin point
  7114. * @param p2 (Vector3) the end point of the Hermite Spline
  7115. * @param t2 (Vector3) the tangent vector at the end point
  7116. * @param nbPoints (integer) the wanted number of points in the curve
  7117. */
  7118. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7119. var hermite = new Array();
  7120. var step = 1.0 / nbPoints;
  7121. for (var i = 0; i <= nbPoints; i++) {
  7122. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7123. }
  7124. return new Curve3(hermite);
  7125. };
  7126. /**
  7127. * Returns a Curve3 object along a CatmullRom Spline curve :
  7128. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7129. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7130. */
  7131. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7132. var totalPoints = new Array();
  7133. totalPoints.push(points[0].clone());
  7134. Array.prototype.push.apply(totalPoints, points);
  7135. totalPoints.push(points[points.length - 1].clone());
  7136. var catmullRom = new Array();
  7137. var step = 1.0 / nbPoints;
  7138. var amount = 0.0;
  7139. for (var i = 0; i < totalPoints.length - 3; i++) {
  7140. amount = 0;
  7141. for (var c = 0; c < nbPoints; c++) {
  7142. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7143. amount += step;
  7144. }
  7145. }
  7146. i--;
  7147. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7148. return new Curve3(catmullRom);
  7149. };
  7150. /**
  7151. * Returns the Curve3 stored array of successive Vector3
  7152. */
  7153. Curve3.prototype.getPoints = function () {
  7154. return this._points;
  7155. };
  7156. /**
  7157. * Returns the computed length (float) of the curve.
  7158. */
  7159. Curve3.prototype.length = function () {
  7160. return this._length;
  7161. };
  7162. /**
  7163. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7164. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7165. * curveA and curveB keep unchanged.
  7166. */
  7167. Curve3.prototype.continue = function (curve) {
  7168. var lastPoint = this._points[this._points.length - 1];
  7169. var continuedPoints = this._points.slice();
  7170. var curvePoints = curve.getPoints();
  7171. for (var i = 1; i < curvePoints.length; i++) {
  7172. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7173. }
  7174. var continuedCurve = new Curve3(continuedPoints);
  7175. return continuedCurve;
  7176. };
  7177. Curve3.prototype._computeLength = function (path) {
  7178. var l = 0;
  7179. for (var i = 1; i < path.length; i++) {
  7180. l += (path[i].subtract(path[i - 1])).length();
  7181. }
  7182. return l;
  7183. };
  7184. return Curve3;
  7185. }());
  7186. BABYLON.Curve3 = Curve3;
  7187. // Vertex formats
  7188. var PositionNormalVertex = /** @class */ (function () {
  7189. function PositionNormalVertex(position, normal) {
  7190. if (position === void 0) { position = Vector3.Zero(); }
  7191. if (normal === void 0) { normal = Vector3.Up(); }
  7192. this.position = position;
  7193. this.normal = normal;
  7194. }
  7195. PositionNormalVertex.prototype.clone = function () {
  7196. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7197. };
  7198. return PositionNormalVertex;
  7199. }());
  7200. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7201. var PositionNormalTextureVertex = /** @class */ (function () {
  7202. function PositionNormalTextureVertex(position, normal, uv) {
  7203. if (position === void 0) { position = Vector3.Zero(); }
  7204. if (normal === void 0) { normal = Vector3.Up(); }
  7205. if (uv === void 0) { uv = Vector2.Zero(); }
  7206. this.position = position;
  7207. this.normal = normal;
  7208. this.uv = uv;
  7209. }
  7210. PositionNormalTextureVertex.prototype.clone = function () {
  7211. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7212. };
  7213. return PositionNormalTextureVertex;
  7214. }());
  7215. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7216. // Temporary pre-allocated objects for engine internal use
  7217. // usage in any internal function :
  7218. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7219. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7220. var Tmp = /** @class */ (function () {
  7221. function Tmp() {
  7222. }
  7223. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7224. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7225. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7226. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7227. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7228. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7229. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7230. Matrix.Zero(), Matrix.Zero(),
  7231. Matrix.Zero(), Matrix.Zero(),
  7232. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7233. return Tmp;
  7234. }());
  7235. BABYLON.Tmp = Tmp;
  7236. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7237. var MathTmp = /** @class */ (function () {
  7238. function MathTmp() {
  7239. }
  7240. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7241. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7242. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7243. return MathTmp;
  7244. }());
  7245. })(BABYLON || (BABYLON = {}));
  7246. //# sourceMappingURL=babylon.math.js.map
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var Scalar = /** @class */ (function () {
  7250. function Scalar() {
  7251. }
  7252. /**
  7253. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7254. */
  7255. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7256. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7257. var num = a - b;
  7258. return -epsilon <= num && num <= epsilon;
  7259. };
  7260. /**
  7261. * Returns a string : the upper case translation of the number i to hexadecimal.
  7262. */
  7263. Scalar.ToHex = function (i) {
  7264. var str = i.toString(16);
  7265. if (i <= 15) {
  7266. return ("0" + str).toUpperCase();
  7267. }
  7268. return str.toUpperCase();
  7269. };
  7270. /**
  7271. * Returns -1 if value is negative and +1 is value is positive.
  7272. * Returns the value itself if it's equal to zero.
  7273. */
  7274. Scalar.Sign = function (value) {
  7275. value = +value; // convert to a number
  7276. if (value === 0 || isNaN(value))
  7277. return value;
  7278. return value > 0 ? 1 : -1;
  7279. };
  7280. /**
  7281. * Returns the value itself if it's between min and max.
  7282. * Returns min if the value is lower than min.
  7283. * Returns max if the value is greater than max.
  7284. */
  7285. Scalar.Clamp = function (value, min, max) {
  7286. if (min === void 0) { min = 0; }
  7287. if (max === void 0) { max = 1; }
  7288. return Math.min(max, Math.max(min, value));
  7289. };
  7290. /**
  7291. * Returns the log2 of value.
  7292. */
  7293. Scalar.Log2 = function (value) {
  7294. return Math.log(value) * Math.LOG2E;
  7295. };
  7296. /**
  7297. * Loops the value, so that it is never larger than length and never smaller than 0.
  7298. *
  7299. * This is similar to the modulo operator but it works with floating point numbers.
  7300. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7301. * With t = 5 and length = 2.5, the result would be 0.0.
  7302. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7303. */
  7304. Scalar.Repeat = function (value, length) {
  7305. return value - Math.floor(value / length) * length;
  7306. };
  7307. /**
  7308. * Normalize the value between 0.0 and 1.0 using min and max values
  7309. */
  7310. Scalar.Normalize = function (value, min, max) {
  7311. return (value - min) / (max - min);
  7312. };
  7313. /**
  7314. * Denormalize the value from 0.0 and 1.0 using min and max values
  7315. */
  7316. Scalar.Denormalize = function (normalized, min, max) {
  7317. return (normalized * (max - min) + min);
  7318. };
  7319. /**
  7320. * Calculates the shortest difference between two given angles given in degrees.
  7321. */
  7322. Scalar.DeltaAngle = function (current, target) {
  7323. var num = Scalar.Repeat(target - current, 360.0);
  7324. if (num > 180.0) {
  7325. num -= 360.0;
  7326. }
  7327. return num;
  7328. };
  7329. /**
  7330. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7331. *
  7332. * The returned value will move back and forth between 0 and length
  7333. */
  7334. Scalar.PingPong = function (tx, length) {
  7335. var t = Scalar.Repeat(tx, length * 2.0);
  7336. return length - Math.abs(t - length);
  7337. };
  7338. /**
  7339. * Interpolates between min and max with smoothing at the limits.
  7340. *
  7341. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7342. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7343. */
  7344. Scalar.SmoothStep = function (from, to, tx) {
  7345. var t = Scalar.Clamp(tx);
  7346. t = -2.0 * t * t * t + 3.0 * t * t;
  7347. return to * t + from * (1.0 - t);
  7348. };
  7349. /**
  7350. * Moves a value current towards target.
  7351. *
  7352. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7353. * Negative values of maxDelta pushes the value away from target.
  7354. */
  7355. Scalar.MoveTowards = function (current, target, maxDelta) {
  7356. var result = 0;
  7357. if (Math.abs(target - current) <= maxDelta) {
  7358. result = target;
  7359. }
  7360. else {
  7361. result = current + Scalar.Sign(target - current) * maxDelta;
  7362. }
  7363. return result;
  7364. };
  7365. /**
  7366. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7367. *
  7368. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7369. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7370. */
  7371. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7372. var num = Scalar.DeltaAngle(current, target);
  7373. var result = 0;
  7374. if (-maxDelta < num && num < maxDelta) {
  7375. result = target;
  7376. }
  7377. else {
  7378. target = current + num;
  7379. result = Scalar.MoveTowards(current, target, maxDelta);
  7380. }
  7381. return result;
  7382. };
  7383. /**
  7384. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7385. */
  7386. Scalar.Lerp = function (start, end, amount) {
  7387. return start + ((end - start) * amount);
  7388. };
  7389. /**
  7390. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7391. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7392. */
  7393. Scalar.LerpAngle = function (start, end, amount) {
  7394. var num = Scalar.Repeat(end - start, 360.0);
  7395. if (num > 180.0) {
  7396. num -= 360.0;
  7397. }
  7398. return start + num * Scalar.Clamp(amount);
  7399. };
  7400. /**
  7401. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7402. */
  7403. Scalar.InverseLerp = function (a, b, value) {
  7404. var result = 0;
  7405. if (a != b) {
  7406. result = Scalar.Clamp((value - a) / (b - a));
  7407. }
  7408. else {
  7409. result = 0.0;
  7410. }
  7411. return result;
  7412. };
  7413. /**
  7414. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7415. */
  7416. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7417. var squared = amount * amount;
  7418. var cubed = amount * squared;
  7419. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7420. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7421. var part3 = (cubed - (2.0 * squared)) + amount;
  7422. var part4 = cubed - squared;
  7423. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7424. };
  7425. /**
  7426. * Returns a random float number between and min and max values
  7427. */
  7428. Scalar.RandomRange = function (min, max) {
  7429. if (min === max)
  7430. return min;
  7431. return ((Math.random() * (max - min)) + min);
  7432. };
  7433. /**
  7434. * This function returns percentage of a number in a given range.
  7435. *
  7436. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7437. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7438. */
  7439. Scalar.RangeToPercent = function (number, min, max) {
  7440. return ((number - min) / (max - min));
  7441. };
  7442. /**
  7443. * This function returns number that corresponds to the percentage in a given range.
  7444. *
  7445. * PercentToRange(0.34,0,100) will return 34.
  7446. */
  7447. Scalar.PercentToRange = function (percent, min, max) {
  7448. return ((max - min) * percent + min);
  7449. };
  7450. /**
  7451. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7452. * @param angle The angle to normalize in radian.
  7453. * @return The converted angle.
  7454. */
  7455. Scalar.NormalizeRadians = function (angle) {
  7456. // More precise but slower version kept for reference.
  7457. // angle = angle % Tools.TwoPi;
  7458. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7459. //if (angle > Math.PI) {
  7460. // angle -= Tools.TwoPi;
  7461. //}
  7462. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7463. return angle;
  7464. };
  7465. /**
  7466. * Two pi constants convenient for computation.
  7467. */
  7468. Scalar.TwoPi = Math.PI * 2;
  7469. return Scalar;
  7470. }());
  7471. BABYLON.Scalar = Scalar;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.math.scalar.js.map
  7474. //# sourceMappingURL=babylon.mixins.js.map
  7475. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7476. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7477. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7478. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7479. //# sourceMappingURL=babylon.webgl2.js.map
  7480. var BABYLON;
  7481. (function (BABYLON) {
  7482. var __decoratorInitialStore = {};
  7483. var __mergedStore = {};
  7484. var _copySource = function (creationFunction, source, instanciate) {
  7485. var destination = creationFunction();
  7486. // Tags
  7487. if (BABYLON.Tags) {
  7488. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7489. }
  7490. var classStore = getMergedStore(destination);
  7491. // Properties
  7492. for (var property in classStore) {
  7493. var propertyDescriptor = classStore[property];
  7494. var sourceProperty = source[property];
  7495. var propertyType = propertyDescriptor.type;
  7496. if (sourceProperty !== undefined && sourceProperty !== null) {
  7497. switch (propertyType) {
  7498. case 0: // Value
  7499. case 6: // Mesh reference
  7500. case 11: // Camera reference
  7501. destination[property] = sourceProperty;
  7502. break;
  7503. case 1: // Texture
  7504. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7505. break;
  7506. case 2: // Color3
  7507. case 3: // FresnelParameters
  7508. case 4: // Vector2
  7509. case 5: // Vector3
  7510. case 7: // Color Curves
  7511. case 10: // Quaternion
  7512. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7513. break;
  7514. }
  7515. }
  7516. }
  7517. return destination;
  7518. };
  7519. function getDirectStore(target) {
  7520. var classKey = target.getClassName();
  7521. if (!__decoratorInitialStore[classKey]) {
  7522. __decoratorInitialStore[classKey] = {};
  7523. }
  7524. return __decoratorInitialStore[classKey];
  7525. }
  7526. /**
  7527. * Return the list of properties flagged as serializable
  7528. * @param target: host object
  7529. */
  7530. function getMergedStore(target) {
  7531. var classKey = target.getClassName();
  7532. if (__mergedStore[classKey]) {
  7533. return __mergedStore[classKey];
  7534. }
  7535. __mergedStore[classKey] = {};
  7536. var store = __mergedStore[classKey];
  7537. var currentTarget = target;
  7538. var currentKey = classKey;
  7539. while (currentKey) {
  7540. var initialStore = __decoratorInitialStore[currentKey];
  7541. for (var property in initialStore) {
  7542. store[property] = initialStore[property];
  7543. }
  7544. var parent_1 = void 0;
  7545. var done = false;
  7546. do {
  7547. parent_1 = Object.getPrototypeOf(currentTarget);
  7548. if (!parent_1.getClassName) {
  7549. done = true;
  7550. break;
  7551. }
  7552. if (parent_1.getClassName() !== currentKey) {
  7553. break;
  7554. }
  7555. currentTarget = parent_1;
  7556. } while (parent_1);
  7557. if (done) {
  7558. break;
  7559. }
  7560. currentKey = parent_1.getClassName();
  7561. currentTarget = parent_1;
  7562. }
  7563. return store;
  7564. }
  7565. function generateSerializableMember(type, sourceName) {
  7566. return function (target, propertyKey) {
  7567. var classStore = getDirectStore(target);
  7568. if (!classStore[propertyKey]) {
  7569. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7570. }
  7571. };
  7572. }
  7573. function generateExpandMember(setCallback, targetKey) {
  7574. if (targetKey === void 0) { targetKey = null; }
  7575. return function (target, propertyKey) {
  7576. var key = targetKey || ("_" + propertyKey);
  7577. Object.defineProperty(target, propertyKey, {
  7578. get: function () {
  7579. return this[key];
  7580. },
  7581. set: function (value) {
  7582. if (this[key] === value) {
  7583. return;
  7584. }
  7585. this[key] = value;
  7586. target[setCallback].apply(this);
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. };
  7592. }
  7593. function expandToProperty(callback, targetKey) {
  7594. if (targetKey === void 0) { targetKey = null; }
  7595. return generateExpandMember(callback, targetKey);
  7596. }
  7597. BABYLON.expandToProperty = expandToProperty;
  7598. function serialize(sourceName) {
  7599. return generateSerializableMember(0, sourceName); // value member
  7600. }
  7601. BABYLON.serialize = serialize;
  7602. function serializeAsTexture(sourceName) {
  7603. return generateSerializableMember(1, sourceName); // texture member
  7604. }
  7605. BABYLON.serializeAsTexture = serializeAsTexture;
  7606. function serializeAsColor3(sourceName) {
  7607. return generateSerializableMember(2, sourceName); // color3 member
  7608. }
  7609. BABYLON.serializeAsColor3 = serializeAsColor3;
  7610. function serializeAsFresnelParameters(sourceName) {
  7611. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7612. }
  7613. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7614. function serializeAsVector2(sourceName) {
  7615. return generateSerializableMember(4, sourceName); // vector2 member
  7616. }
  7617. BABYLON.serializeAsVector2 = serializeAsVector2;
  7618. function serializeAsVector3(sourceName) {
  7619. return generateSerializableMember(5, sourceName); // vector3 member
  7620. }
  7621. BABYLON.serializeAsVector3 = serializeAsVector3;
  7622. function serializeAsMeshReference(sourceName) {
  7623. return generateSerializableMember(6, sourceName); // mesh reference member
  7624. }
  7625. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7626. function serializeAsColorCurves(sourceName) {
  7627. return generateSerializableMember(7, sourceName); // color curves
  7628. }
  7629. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7630. function serializeAsColor4(sourceName) {
  7631. return generateSerializableMember(8, sourceName); // color 4
  7632. }
  7633. BABYLON.serializeAsColor4 = serializeAsColor4;
  7634. function serializeAsImageProcessingConfiguration(sourceName) {
  7635. return generateSerializableMember(9, sourceName); // image processing
  7636. }
  7637. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7638. function serializeAsQuaternion(sourceName) {
  7639. return generateSerializableMember(10, sourceName); // quaternion member
  7640. }
  7641. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7642. /**
  7643. * Decorator used to define property that can be serialized as reference to a camera
  7644. * @param sourceName defines the name of the property to decorate
  7645. */
  7646. function serializeAsCameraReference(sourceName) {
  7647. return generateSerializableMember(11, sourceName); // camera reference member
  7648. }
  7649. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7650. var SerializationHelper = /** @class */ (function () {
  7651. function SerializationHelper() {
  7652. }
  7653. SerializationHelper.Serialize = function (entity, serializationObject) {
  7654. if (!serializationObject) {
  7655. serializationObject = {};
  7656. }
  7657. // Tags
  7658. if (BABYLON.Tags) {
  7659. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7660. }
  7661. var serializedProperties = getMergedStore(entity);
  7662. // Properties
  7663. for (var property in serializedProperties) {
  7664. var propertyDescriptor = serializedProperties[property];
  7665. var targetPropertyName = propertyDescriptor.sourceName || property;
  7666. var propertyType = propertyDescriptor.type;
  7667. var sourceProperty = entity[property];
  7668. if (sourceProperty !== undefined && sourceProperty !== null) {
  7669. switch (propertyType) {
  7670. case 0: // Value
  7671. serializationObject[targetPropertyName] = sourceProperty;
  7672. break;
  7673. case 1: // Texture
  7674. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7675. break;
  7676. case 2: // Color3
  7677. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7678. break;
  7679. case 3: // FresnelParameters
  7680. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7681. break;
  7682. case 4: // Vector2
  7683. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7684. break;
  7685. case 5: // Vector3
  7686. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7687. break;
  7688. case 6: // Mesh reference
  7689. serializationObject[targetPropertyName] = sourceProperty.id;
  7690. break;
  7691. case 7: // Color Curves
  7692. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7693. break;
  7694. case 8: // Color 4
  7695. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7696. break;
  7697. case 9: // Image Processing
  7698. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7699. break;
  7700. case 10: // Quaternion
  7701. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7702. break;
  7703. case 11: // Camera reference
  7704. serializationObject[targetPropertyName] = sourceProperty.id;
  7705. break;
  7706. }
  7707. }
  7708. }
  7709. return serializationObject;
  7710. };
  7711. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7712. if (rootUrl === void 0) { rootUrl = null; }
  7713. var destination = creationFunction();
  7714. if (!rootUrl) {
  7715. rootUrl = "";
  7716. }
  7717. // Tags
  7718. if (BABYLON.Tags) {
  7719. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7720. }
  7721. var classStore = getMergedStore(destination);
  7722. // Properties
  7723. for (var property in classStore) {
  7724. var propertyDescriptor = classStore[property];
  7725. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7726. var propertyType = propertyDescriptor.type;
  7727. if (sourceProperty !== undefined && sourceProperty !== null) {
  7728. var dest = destination;
  7729. switch (propertyType) {
  7730. case 0: // Value
  7731. dest[property] = sourceProperty;
  7732. break;
  7733. case 1: // Texture
  7734. if (scene) {
  7735. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7736. }
  7737. break;
  7738. case 2: // Color3
  7739. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7740. break;
  7741. case 3: // FresnelParameters
  7742. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7743. break;
  7744. case 4: // Vector2
  7745. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7746. break;
  7747. case 5: // Vector3
  7748. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7749. break;
  7750. case 6: // Mesh reference
  7751. if (scene) {
  7752. dest[property] = scene.getLastMeshByID(sourceProperty);
  7753. }
  7754. break;
  7755. case 7: // Color Curves
  7756. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7757. break;
  7758. case 8: // Color 4
  7759. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7760. break;
  7761. case 9: // Image Processing
  7762. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7763. break;
  7764. case 10: // Quaternion
  7765. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7766. break;
  7767. case 11: // Camera reference
  7768. if (scene) {
  7769. dest[property] = scene.getCameraByID(sourceProperty);
  7770. }
  7771. break;
  7772. }
  7773. }
  7774. }
  7775. return destination;
  7776. };
  7777. SerializationHelper.Clone = function (creationFunction, source) {
  7778. return _copySource(creationFunction, source, false);
  7779. };
  7780. SerializationHelper.Instanciate = function (creationFunction, source) {
  7781. return _copySource(creationFunction, source, true);
  7782. };
  7783. return SerializationHelper;
  7784. }());
  7785. BABYLON.SerializationHelper = SerializationHelper;
  7786. })(BABYLON || (BABYLON = {}));
  7787. //# sourceMappingURL=babylon.decorators.js.map
  7788. var BABYLON;
  7789. (function (BABYLON) {
  7790. /**
  7791. * Wrapper class for promise with external resolve and reject.
  7792. */
  7793. var Deferred = /** @class */ (function () {
  7794. /**
  7795. * Constructor for this deferred object.
  7796. */
  7797. function Deferred() {
  7798. var _this = this;
  7799. this.promise = new Promise(function (resolve, reject) {
  7800. _this._resolve = resolve;
  7801. _this._reject = reject;
  7802. });
  7803. }
  7804. Object.defineProperty(Deferred.prototype, "resolve", {
  7805. /**
  7806. * The resolve method of the promise associated with this deferred object.
  7807. */
  7808. get: function () {
  7809. return this._resolve;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Deferred.prototype, "reject", {
  7815. /**
  7816. * The reject method of the promise associated with this deferred object.
  7817. */
  7818. get: function () {
  7819. return this._reject;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. return Deferred;
  7825. }());
  7826. BABYLON.Deferred = Deferred;
  7827. })(BABYLON || (BABYLON = {}));
  7828. //# sourceMappingURL=babylon.deferred.js.map
  7829. var BABYLON;
  7830. (function (BABYLON) {
  7831. /**
  7832. * A class serves as a medium between the observable and its observers
  7833. */
  7834. var EventState = /** @class */ (function () {
  7835. /**
  7836. * Create a new EventState
  7837. * @param mask defines the mask associated with this state
  7838. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7839. * @param target defines the original target of the state
  7840. * @param currentTarget defines the current target of the state
  7841. */
  7842. function EventState(mask, skipNextObservers, target, currentTarget) {
  7843. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7844. this.initalize(mask, skipNextObservers, target, currentTarget);
  7845. }
  7846. /**
  7847. * Initialize the current event state
  7848. * @param mask defines the mask associated with this state
  7849. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7850. * @param target defines the original target of the state
  7851. * @param currentTarget defines the current target of the state
  7852. * @returns the current event state
  7853. */
  7854. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7855. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7856. this.mask = mask;
  7857. this.skipNextObservers = skipNextObservers;
  7858. this.target = target;
  7859. this.currentTarget = currentTarget;
  7860. return this;
  7861. };
  7862. return EventState;
  7863. }());
  7864. BABYLON.EventState = EventState;
  7865. /**
  7866. * Represent an Observer registered to a given Observable object.
  7867. */
  7868. var Observer = /** @class */ (function () {
  7869. /**
  7870. * Creates a new observer
  7871. * @param callback defines the callback to call when the observer is notified
  7872. * @param mask defines the mask of the observer (used to filter notifications)
  7873. * @param scope defines the current scope used to restore the JS context
  7874. */
  7875. function Observer(
  7876. /**
  7877. * Defines the callback to call when the observer is notified
  7878. */
  7879. callback,
  7880. /**
  7881. * Defines the mask of the observer (used to filter notifications)
  7882. */
  7883. mask,
  7884. /**
  7885. * Defines the current scope used to restore the JS context
  7886. */
  7887. scope) {
  7888. if (scope === void 0) { scope = null; }
  7889. this.callback = callback;
  7890. this.mask = mask;
  7891. this.scope = scope;
  7892. /** @ignore */
  7893. this._willBeUnregistered = false;
  7894. /**
  7895. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7896. */
  7897. this.unregisterOnNextCall = false;
  7898. }
  7899. return Observer;
  7900. }());
  7901. BABYLON.Observer = Observer;
  7902. /**
  7903. * Represent a list of observers registered to multiple Observables object.
  7904. */
  7905. var MultiObserver = /** @class */ (function () {
  7906. function MultiObserver() {
  7907. }
  7908. /**
  7909. * Release associated resources
  7910. */
  7911. MultiObserver.prototype.dispose = function () {
  7912. if (this._observers && this._observables) {
  7913. for (var index = 0; index < this._observers.length; index++) {
  7914. this._observables[index].remove(this._observers[index]);
  7915. }
  7916. }
  7917. this._observers = null;
  7918. this._observables = null;
  7919. };
  7920. /**
  7921. * Raise a callback when one of the observable will notify
  7922. * @param observables defines a list of observables to watch
  7923. * @param callback defines the callback to call on notification
  7924. * @param mask defines the mask used to filter notifications
  7925. * @param scope defines the current scope used to restore the JS context
  7926. * @returns the new MultiObserver
  7927. */
  7928. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7929. if (mask === void 0) { mask = -1; }
  7930. if (scope === void 0) { scope = null; }
  7931. var result = new MultiObserver();
  7932. result._observers = new Array();
  7933. result._observables = observables;
  7934. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7935. var observable = observables_1[_i];
  7936. var observer = observable.add(callback, mask, false, scope);
  7937. if (observer) {
  7938. result._observers.push(observer);
  7939. }
  7940. }
  7941. return result;
  7942. };
  7943. return MultiObserver;
  7944. }());
  7945. BABYLON.MultiObserver = MultiObserver;
  7946. /**
  7947. * The Observable class is a simple implementation of the Observable pattern.
  7948. *
  7949. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7950. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7951. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7952. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7953. */
  7954. var Observable = /** @class */ (function () {
  7955. /**
  7956. * Creates a new observable
  7957. * @param onObserverAdded defines a callback to call when a new observer is added
  7958. */
  7959. function Observable(onObserverAdded) {
  7960. this._observers = new Array();
  7961. this._eventState = new EventState(0);
  7962. if (onObserverAdded) {
  7963. this._onObserverAdded = onObserverAdded;
  7964. }
  7965. }
  7966. /**
  7967. * Create a new Observer with the specified callback
  7968. * @param callback the callback that will be executed for that Observer
  7969. * @param mask the mask used to filter observers
  7970. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7971. * @param scope optional scope for the callback to be called from
  7972. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7973. * @returns the new observer created for the callback
  7974. */
  7975. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7976. if (mask === void 0) { mask = -1; }
  7977. if (insertFirst === void 0) { insertFirst = false; }
  7978. if (scope === void 0) { scope = null; }
  7979. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7980. if (!callback) {
  7981. return null;
  7982. }
  7983. var observer = new Observer(callback, mask, scope);
  7984. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7985. if (insertFirst) {
  7986. this._observers.unshift(observer);
  7987. }
  7988. else {
  7989. this._observers.push(observer);
  7990. }
  7991. if (this._onObserverAdded) {
  7992. this._onObserverAdded(observer);
  7993. }
  7994. return observer;
  7995. };
  7996. /**
  7997. * Remove an Observer from the Observable object
  7998. * @param observer the instance of the Observer to remove
  7999. * @returns false if it doesn't belong to this Observable
  8000. */
  8001. Observable.prototype.remove = function (observer) {
  8002. if (!observer) {
  8003. return false;
  8004. }
  8005. var index = this._observers.indexOf(observer);
  8006. if (index !== -1) {
  8007. this._observers.splice(index, 1);
  8008. return true;
  8009. }
  8010. return false;
  8011. };
  8012. /**
  8013. * Remove a callback from the Observable object
  8014. * @param callback the callback to remove
  8015. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8016. * @returns false if it doesn't belong to this Observable
  8017. */
  8018. Observable.prototype.removeCallback = function (callback, scope) {
  8019. for (var index = 0; index < this._observers.length; index++) {
  8020. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8021. this._observers.splice(index, 1);
  8022. return true;
  8023. }
  8024. }
  8025. return false;
  8026. };
  8027. Observable.prototype._deferUnregister = function (observer) {
  8028. var _this = this;
  8029. observer.unregisterOnNextCall = false;
  8030. observer._willBeUnregistered = true;
  8031. BABYLON.Tools.SetImmediate(function () {
  8032. _this.remove(observer);
  8033. });
  8034. };
  8035. /**
  8036. * Notify all Observers by calling their respective callback with the given data
  8037. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8038. * @param eventData defines the data to send to all observers
  8039. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8040. * @param target defines the original target of the state
  8041. * @param currentTarget defines the current target of the state
  8042. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8043. */
  8044. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8045. if (mask === void 0) { mask = -1; }
  8046. if (!this._observers.length) {
  8047. return true;
  8048. }
  8049. var state = this._eventState;
  8050. state.mask = mask;
  8051. state.target = target;
  8052. state.currentTarget = currentTarget;
  8053. state.skipNextObservers = false;
  8054. state.lastReturnValue = eventData;
  8055. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8056. var obs = _a[_i];
  8057. if (obs._willBeUnregistered) {
  8058. continue;
  8059. }
  8060. if (obs.mask & mask) {
  8061. if (obs.scope) {
  8062. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8063. }
  8064. else {
  8065. state.lastReturnValue = obs.callback(eventData, state);
  8066. }
  8067. if (obs.unregisterOnNextCall) {
  8068. this._deferUnregister(obs);
  8069. }
  8070. }
  8071. if (state.skipNextObservers) {
  8072. return false;
  8073. }
  8074. }
  8075. return true;
  8076. };
  8077. /**
  8078. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8079. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8080. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8081. * and it is crucial that all callbacks will be executed.
  8082. * The order of the callbacks is kept, callbacks are not executed parallel.
  8083. *
  8084. * @param eventData The data to be sent to each callback
  8085. * @param mask is used to filter observers defaults to -1
  8086. * @param target defines the callback target (see EventState)
  8087. * @param currentTarget defines he current object in the bubbling phase
  8088. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8089. */
  8090. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8091. var _this = this;
  8092. if (mask === void 0) { mask = -1; }
  8093. // create an empty promise
  8094. var p = Promise.resolve(eventData);
  8095. // no observers? return this promise.
  8096. if (!this._observers.length) {
  8097. return p;
  8098. }
  8099. var state = this._eventState;
  8100. state.mask = mask;
  8101. state.target = target;
  8102. state.currentTarget = currentTarget;
  8103. state.skipNextObservers = false;
  8104. // execute one callback after another (not using Promise.all, the order is important)
  8105. this._observers.forEach(function (obs) {
  8106. if (state.skipNextObservers) {
  8107. return;
  8108. }
  8109. if (obs._willBeUnregistered) {
  8110. return;
  8111. }
  8112. if (obs.mask & mask) {
  8113. if (obs.scope) {
  8114. p = p.then(function (lastReturnedValue) {
  8115. state.lastReturnValue = lastReturnedValue;
  8116. return obs.callback.apply(obs.scope, [eventData, state]);
  8117. });
  8118. }
  8119. else {
  8120. p = p.then(function (lastReturnedValue) {
  8121. state.lastReturnValue = lastReturnedValue;
  8122. return obs.callback(eventData, state);
  8123. });
  8124. }
  8125. if (obs.unregisterOnNextCall) {
  8126. _this._deferUnregister(obs);
  8127. }
  8128. }
  8129. });
  8130. // return the eventData
  8131. return p.then(function () { return eventData; });
  8132. };
  8133. /**
  8134. * Notify a specific observer
  8135. * @param observer defines the observer to notify
  8136. * @param eventData defines the data to be sent to each callback
  8137. * @param mask is used to filter observers defaults to -1
  8138. */
  8139. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8140. if (mask === void 0) { mask = -1; }
  8141. var state = this._eventState;
  8142. state.mask = mask;
  8143. state.skipNextObservers = false;
  8144. observer.callback(eventData, state);
  8145. };
  8146. /**
  8147. * Gets a boolean indicating if the observable has at least one observer
  8148. * @returns true is the Observable has at least one Observer registered
  8149. */
  8150. Observable.prototype.hasObservers = function () {
  8151. return this._observers.length > 0;
  8152. };
  8153. /**
  8154. * Clear the list of observers
  8155. */
  8156. Observable.prototype.clear = function () {
  8157. this._observers = new Array();
  8158. this._onObserverAdded = null;
  8159. };
  8160. /**
  8161. * Clone the current observable
  8162. * @returns a new observable
  8163. */
  8164. Observable.prototype.clone = function () {
  8165. var result = new Observable();
  8166. result._observers = this._observers.slice(0);
  8167. return result;
  8168. };
  8169. /**
  8170. * Does this observable handles observer registered with a given mask
  8171. * @param mask defines the mask to be tested
  8172. * @return whether or not one observer registered with the given mask is handeled
  8173. **/
  8174. Observable.prototype.hasSpecificMask = function (mask) {
  8175. if (mask === void 0) { mask = -1; }
  8176. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8177. var obs = _a[_i];
  8178. if (obs.mask & mask || obs.mask === mask) {
  8179. return true;
  8180. }
  8181. }
  8182. return false;
  8183. };
  8184. return Observable;
  8185. }());
  8186. BABYLON.Observable = Observable;
  8187. })(BABYLON || (BABYLON = {}));
  8188. //# sourceMappingURL=babylon.observable.js.map
  8189. var BABYLON;
  8190. (function (BABYLON) {
  8191. var SmartArray = /** @class */ (function () {
  8192. function SmartArray(capacity) {
  8193. this.length = 0;
  8194. this.data = new Array(capacity);
  8195. this._id = SmartArray._GlobalId++;
  8196. }
  8197. SmartArray.prototype.push = function (value) {
  8198. this.data[this.length++] = value;
  8199. if (this.length > this.data.length) {
  8200. this.data.length *= 2;
  8201. }
  8202. };
  8203. SmartArray.prototype.forEach = function (func) {
  8204. for (var index = 0; index < this.length; index++) {
  8205. func(this.data[index]);
  8206. }
  8207. };
  8208. SmartArray.prototype.sort = function (compareFn) {
  8209. this.data.sort(compareFn);
  8210. };
  8211. SmartArray.prototype.reset = function () {
  8212. this.length = 0;
  8213. };
  8214. SmartArray.prototype.dispose = function () {
  8215. this.reset();
  8216. if (this.data) {
  8217. this.data.length = 0;
  8218. this.data = [];
  8219. }
  8220. };
  8221. SmartArray.prototype.concat = function (array) {
  8222. if (array.length === 0) {
  8223. return;
  8224. }
  8225. if (this.length + array.length > this.data.length) {
  8226. this.data.length = (this.length + array.length) * 2;
  8227. }
  8228. for (var index = 0; index < array.length; index++) {
  8229. this.data[this.length++] = (array.data || array)[index];
  8230. }
  8231. };
  8232. SmartArray.prototype.indexOf = function (value) {
  8233. var position = this.data.indexOf(value);
  8234. if (position >= this.length) {
  8235. return -1;
  8236. }
  8237. return position;
  8238. };
  8239. SmartArray.prototype.contains = function (value) {
  8240. return this.data.indexOf(value) !== -1;
  8241. };
  8242. // Statics
  8243. SmartArray._GlobalId = 0;
  8244. return SmartArray;
  8245. }());
  8246. BABYLON.SmartArray = SmartArray;
  8247. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8248. __extends(SmartArrayNoDuplicate, _super);
  8249. function SmartArrayNoDuplicate() {
  8250. var _this = _super !== null && _super.apply(this, arguments) || this;
  8251. _this._duplicateId = 0;
  8252. return _this;
  8253. }
  8254. SmartArrayNoDuplicate.prototype.push = function (value) {
  8255. _super.prototype.push.call(this, value);
  8256. if (!value.__smartArrayFlags) {
  8257. value.__smartArrayFlags = {};
  8258. }
  8259. value.__smartArrayFlags[this._id] = this._duplicateId;
  8260. };
  8261. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8262. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8263. return false;
  8264. }
  8265. this.push(value);
  8266. return true;
  8267. };
  8268. SmartArrayNoDuplicate.prototype.reset = function () {
  8269. _super.prototype.reset.call(this);
  8270. this._duplicateId++;
  8271. };
  8272. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8273. if (array.length === 0) {
  8274. return;
  8275. }
  8276. if (this.length + array.length > this.data.length) {
  8277. this.data.length = (this.length + array.length) * 2;
  8278. }
  8279. for (var index = 0; index < array.length; index++) {
  8280. var item = (array.data || array)[index];
  8281. this.pushNoDuplicate(item);
  8282. }
  8283. };
  8284. return SmartArrayNoDuplicate;
  8285. }(SmartArray));
  8286. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8287. })(BABYLON || (BABYLON = {}));
  8288. //# sourceMappingURL=babylon.smartArray.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8292. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8293. var LoadFileError = /** @class */ (function (_super) {
  8294. __extends(LoadFileError, _super);
  8295. function LoadFileError(message, request) {
  8296. var _this = _super.call(this, message) || this;
  8297. _this.request = request;
  8298. _this.name = "LoadFileError";
  8299. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8300. return _this;
  8301. }
  8302. // Polyfill for Object.setPrototypeOf if necessary.
  8303. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8304. return LoadFileError;
  8305. }(Error));
  8306. BABYLON.LoadFileError = LoadFileError;
  8307. var RetryStrategy = /** @class */ (function () {
  8308. function RetryStrategy() {
  8309. }
  8310. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8311. if (maxRetries === void 0) { maxRetries = 3; }
  8312. if (baseInterval === void 0) { baseInterval = 500; }
  8313. return function (url, request, retryIndex) {
  8314. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8315. return -1;
  8316. }
  8317. return Math.pow(2, retryIndex) * baseInterval;
  8318. };
  8319. };
  8320. return RetryStrategy;
  8321. }());
  8322. BABYLON.RetryStrategy = RetryStrategy;
  8323. // Screenshots
  8324. var screenshotCanvas;
  8325. var cloneValue = function (source, destinationObject) {
  8326. if (!source)
  8327. return null;
  8328. if (source instanceof BABYLON.Mesh) {
  8329. return null;
  8330. }
  8331. if (source instanceof BABYLON.SubMesh) {
  8332. return source.clone(destinationObject);
  8333. }
  8334. else if (source.clone) {
  8335. return source.clone();
  8336. }
  8337. return null;
  8338. };
  8339. var Tools = /** @class */ (function () {
  8340. function Tools() {
  8341. }
  8342. /**
  8343. * Interpolates between a and b via alpha
  8344. * @param a The lower value (returned when alpha = 0)
  8345. * @param b The upper value (returned when alpha = 1)
  8346. * @param alpha The interpolation-factor
  8347. * @return The mixed value
  8348. */
  8349. Tools.Mix = function (a, b, alpha) {
  8350. return a * (1 - alpha) + b * alpha;
  8351. };
  8352. Tools.Instantiate = function (className) {
  8353. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8354. return Tools.RegisteredExternalClasses[className];
  8355. }
  8356. var arr = className.split(".");
  8357. var fn = (window || this);
  8358. for (var i = 0, len = arr.length; i < len; i++) {
  8359. fn = fn[arr[i]];
  8360. }
  8361. if (typeof fn !== "function") {
  8362. return null;
  8363. }
  8364. return fn;
  8365. };
  8366. /**
  8367. * Provides a slice function that will work even on IE
  8368. * @param data defines the array to slice
  8369. * @param start defines the start of the data (optional)
  8370. * @param end defines the end of the data (optional)
  8371. * @returns the new sliced array
  8372. */
  8373. Tools.Slice = function (data, start, end) {
  8374. if (data.slice) {
  8375. return data.slice(start, end);
  8376. }
  8377. return Array.prototype.slice.call(data, start, end);
  8378. };
  8379. Tools.SetImmediate = function (action) {
  8380. if (window.setImmediate) {
  8381. window.setImmediate(action);
  8382. }
  8383. else {
  8384. setTimeout(action, 1);
  8385. }
  8386. };
  8387. Tools.IsExponentOfTwo = function (value) {
  8388. var count = 1;
  8389. do {
  8390. count *= 2;
  8391. } while (count < value);
  8392. return count === value;
  8393. };
  8394. /**
  8395. * Find the next highest power of two.
  8396. * @param x Number to start search from.
  8397. * @return Next highest power of two.
  8398. */
  8399. Tools.CeilingPOT = function (x) {
  8400. x--;
  8401. x |= x >> 1;
  8402. x |= x >> 2;
  8403. x |= x >> 4;
  8404. x |= x >> 8;
  8405. x |= x >> 16;
  8406. x++;
  8407. return x;
  8408. };
  8409. /**
  8410. * Find the next lowest power of two.
  8411. * @param x Number to start search from.
  8412. * @return Next lowest power of two.
  8413. */
  8414. Tools.FloorPOT = function (x) {
  8415. x = x | (x >> 1);
  8416. x = x | (x >> 2);
  8417. x = x | (x >> 4);
  8418. x = x | (x >> 8);
  8419. x = x | (x >> 16);
  8420. return x - (x >> 1);
  8421. };
  8422. /**
  8423. * Find the nearest power of two.
  8424. * @param x Number to start search from.
  8425. * @return Next nearest power of two.
  8426. */
  8427. Tools.NearestPOT = function (x) {
  8428. var c = Tools.CeilingPOT(x);
  8429. var f = Tools.FloorPOT(x);
  8430. return (c - x) > (x - f) ? f : c;
  8431. };
  8432. Tools.GetExponentOfTwo = function (value, max, mode) {
  8433. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8434. var pot;
  8435. switch (mode) {
  8436. case BABYLON.Engine.SCALEMODE_FLOOR:
  8437. pot = Tools.FloorPOT(value);
  8438. break;
  8439. case BABYLON.Engine.SCALEMODE_NEAREST:
  8440. pot = Tools.NearestPOT(value);
  8441. break;
  8442. case BABYLON.Engine.SCALEMODE_CEILING:
  8443. default:
  8444. pot = Tools.CeilingPOT(value);
  8445. break;
  8446. }
  8447. return Math.min(pot, max);
  8448. };
  8449. Tools.GetFilename = function (path) {
  8450. var index = path.lastIndexOf("/");
  8451. if (index < 0)
  8452. return path;
  8453. return path.substring(index + 1);
  8454. };
  8455. /**
  8456. * Extracts the "folder" part of a path (everything before the filename).
  8457. * @param uri The URI to extract the info from
  8458. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8459. * @returns The "folder" part of the path
  8460. */
  8461. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8462. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8463. var index = uri.lastIndexOf("/");
  8464. if (index < 0) {
  8465. if (returnUnchangedIfNoSlash) {
  8466. return uri;
  8467. }
  8468. return "";
  8469. }
  8470. return uri.substring(0, index + 1);
  8471. };
  8472. Tools.GetDOMTextContent = function (element) {
  8473. var result = "";
  8474. var child = element.firstChild;
  8475. while (child) {
  8476. if (child.nodeType === 3) {
  8477. result += child.textContent;
  8478. }
  8479. child = child.nextSibling;
  8480. }
  8481. return result;
  8482. };
  8483. Tools.ToDegrees = function (angle) {
  8484. return angle * 180 / Math.PI;
  8485. };
  8486. Tools.ToRadians = function (angle) {
  8487. return angle * Math.PI / 180;
  8488. };
  8489. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8490. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8491. var output = "";
  8492. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8493. var i = 0;
  8494. var bytes = new Uint8Array(buffer);
  8495. while (i < bytes.length) {
  8496. chr1 = bytes[i++];
  8497. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8498. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8499. enc1 = chr1 >> 2;
  8500. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8501. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8502. enc4 = chr3 & 63;
  8503. if (isNaN(chr2)) {
  8504. enc3 = enc4 = 64;
  8505. }
  8506. else if (isNaN(chr3)) {
  8507. enc4 = 64;
  8508. }
  8509. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8510. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8511. }
  8512. return "data:image/png;base64," + output;
  8513. };
  8514. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8515. if (bias === void 0) { bias = null; }
  8516. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8517. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8518. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8519. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8520. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8521. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8522. }
  8523. if (bias) {
  8524. minimum.x -= minimum.x * bias.x + bias.y;
  8525. minimum.y -= minimum.y * bias.x + bias.y;
  8526. minimum.z -= minimum.z * bias.x + bias.y;
  8527. maximum.x += maximum.x * bias.x + bias.y;
  8528. maximum.y += maximum.y * bias.x + bias.y;
  8529. maximum.z += maximum.z * bias.x + bias.y;
  8530. }
  8531. return {
  8532. minimum: minimum,
  8533. maximum: maximum
  8534. };
  8535. };
  8536. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8537. if (bias === void 0) { bias = null; }
  8538. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8539. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8540. if (!stride) {
  8541. stride = 3;
  8542. }
  8543. for (var index = start; index < start + count; index++) {
  8544. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8545. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8546. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8547. }
  8548. if (bias) {
  8549. minimum.x -= minimum.x * bias.x + bias.y;
  8550. minimum.y -= minimum.y * bias.x + bias.y;
  8551. minimum.z -= minimum.z * bias.x + bias.y;
  8552. maximum.x += maximum.x * bias.x + bias.y;
  8553. maximum.y += maximum.y * bias.x + bias.y;
  8554. maximum.z += maximum.z * bias.x + bias.y;
  8555. }
  8556. return {
  8557. minimum: minimum,
  8558. maximum: maximum
  8559. };
  8560. };
  8561. Tools.Vector2ArrayFeeder = function (array) {
  8562. return function (index) {
  8563. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8564. var length = isFloatArray ? array.length / 2 : array.length;
  8565. if (index >= length) {
  8566. return null;
  8567. }
  8568. if (isFloatArray) {
  8569. var fa = array;
  8570. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8571. }
  8572. var a = array;
  8573. return a[index];
  8574. };
  8575. };
  8576. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8577. if (bias === void 0) { bias = null; }
  8578. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8579. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8580. var i = 0;
  8581. var cur = feeder(i++);
  8582. while (cur) {
  8583. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8584. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8585. cur = feeder(i++);
  8586. }
  8587. if (bias) {
  8588. minimum.x -= minimum.x * bias.x + bias.y;
  8589. minimum.y -= minimum.y * bias.x + bias.y;
  8590. maximum.x += maximum.x * bias.x + bias.y;
  8591. maximum.y += maximum.y * bias.x + bias.y;
  8592. }
  8593. return {
  8594. minimum: minimum,
  8595. maximum: maximum
  8596. };
  8597. };
  8598. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8599. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8600. return null;
  8601. return Array.isArray(obj) ? obj : [obj];
  8602. };
  8603. // Misc.
  8604. Tools.GetPointerPrefix = function () {
  8605. var eventPrefix = "pointer";
  8606. // Check if pointer events are supported
  8607. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8608. eventPrefix = "mouse";
  8609. }
  8610. return eventPrefix;
  8611. };
  8612. /**
  8613. * @param func - the function to be called
  8614. * @param requester - the object that will request the next frame. Falls back to window.
  8615. */
  8616. Tools.QueueNewFrame = function (func, requester) {
  8617. if (!Tools.IsWindowObjectExist()) {
  8618. return setTimeout(func, 16);
  8619. }
  8620. if (!requester) {
  8621. requester = window;
  8622. }
  8623. if (requester.requestAnimationFrame) {
  8624. return requester.requestAnimationFrame(func);
  8625. }
  8626. else if (requester.msRequestAnimationFrame) {
  8627. return requester.msRequestAnimationFrame(func);
  8628. }
  8629. else if (requester.webkitRequestAnimationFrame) {
  8630. return requester.webkitRequestAnimationFrame(func);
  8631. }
  8632. else if (requester.mozRequestAnimationFrame) {
  8633. return requester.mozRequestAnimationFrame(func);
  8634. }
  8635. else if (requester.oRequestAnimationFrame) {
  8636. return requester.oRequestAnimationFrame(func);
  8637. }
  8638. else {
  8639. return window.setTimeout(func, 16);
  8640. }
  8641. };
  8642. Tools.RequestFullscreen = function (element) {
  8643. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8644. if (!requestFunction)
  8645. return;
  8646. requestFunction.call(element);
  8647. };
  8648. Tools.ExitFullscreen = function () {
  8649. if (document.exitFullscreen) {
  8650. document.exitFullscreen();
  8651. }
  8652. else if (document.mozCancelFullScreen) {
  8653. document.mozCancelFullScreen();
  8654. }
  8655. else if (document.webkitCancelFullScreen) {
  8656. document.webkitCancelFullScreen();
  8657. }
  8658. else if (document.msCancelFullScreen) {
  8659. document.msCancelFullScreen();
  8660. }
  8661. };
  8662. Tools.SetCorsBehavior = function (url, element) {
  8663. if (url && url.indexOf("data:") === 0) {
  8664. return;
  8665. }
  8666. if (Tools.CorsBehavior) {
  8667. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8668. element.crossOrigin = Tools.CorsBehavior;
  8669. }
  8670. else {
  8671. var result = Tools.CorsBehavior(url);
  8672. if (result) {
  8673. element.crossOrigin = result;
  8674. }
  8675. }
  8676. }
  8677. };
  8678. // External files
  8679. Tools.CleanUrl = function (url) {
  8680. url = url.replace(/#/mg, "%23");
  8681. return url;
  8682. };
  8683. Tools.LoadImage = function (url, onLoad, onError, database) {
  8684. if (url instanceof ArrayBuffer) {
  8685. url = Tools.EncodeArrayBufferTobase64(url);
  8686. }
  8687. url = Tools.CleanUrl(url);
  8688. url = Tools.PreprocessUrl(url);
  8689. var img = new Image();
  8690. Tools.SetCorsBehavior(url, img);
  8691. var loadHandler = function () {
  8692. img.removeEventListener("load", loadHandler);
  8693. img.removeEventListener("error", errorHandler);
  8694. onLoad(img);
  8695. };
  8696. var errorHandler = function (err) {
  8697. img.removeEventListener("load", loadHandler);
  8698. img.removeEventListener("error", errorHandler);
  8699. Tools.Error("Error while trying to load image: " + url);
  8700. if (onError) {
  8701. onError("Error while trying to load image: " + url, err);
  8702. }
  8703. };
  8704. img.addEventListener("load", loadHandler);
  8705. img.addEventListener("error", errorHandler);
  8706. var noIndexedDB = function () {
  8707. img.src = url;
  8708. };
  8709. var loadFromIndexedDB = function () {
  8710. if (database) {
  8711. database.loadImageFromDB(url, img);
  8712. }
  8713. };
  8714. //ANY database to do!
  8715. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8716. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8717. }
  8718. else {
  8719. if (url.indexOf("file:") !== -1) {
  8720. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8721. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8722. try {
  8723. var blobURL;
  8724. try {
  8725. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8726. }
  8727. catch (ex) {
  8728. // Chrome doesn't support oneTimeOnly parameter
  8729. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8730. }
  8731. img.src = blobURL;
  8732. }
  8733. catch (e) {
  8734. img.src = "";
  8735. }
  8736. return img;
  8737. }
  8738. }
  8739. noIndexedDB();
  8740. }
  8741. return img;
  8742. };
  8743. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8744. url = Tools.CleanUrl(url);
  8745. url = Tools.PreprocessUrl(url);
  8746. // If file and file input are set
  8747. if (url.indexOf("file:") !== -1) {
  8748. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8749. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8750. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8751. }
  8752. }
  8753. var loadUrl = Tools.BaseUrl + url;
  8754. var aborted = false;
  8755. var fileRequest = {
  8756. onCompleteObservable: new BABYLON.Observable(),
  8757. abort: function () { return aborted = true; },
  8758. };
  8759. var requestFile = function () {
  8760. var request = new XMLHttpRequest();
  8761. var retryHandle = null;
  8762. fileRequest.abort = function () {
  8763. aborted = true;
  8764. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8765. request.abort();
  8766. }
  8767. if (retryHandle !== null) {
  8768. clearTimeout(retryHandle);
  8769. retryHandle = null;
  8770. }
  8771. };
  8772. var retryLoop = function (retryIndex) {
  8773. request.open('GET', loadUrl, true);
  8774. if (useArrayBuffer) {
  8775. request.responseType = "arraybuffer";
  8776. }
  8777. if (onProgress) {
  8778. request.addEventListener("progress", onProgress);
  8779. }
  8780. var onLoadEnd = function () {
  8781. request.removeEventListener("loadend", onLoadEnd);
  8782. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8783. fileRequest.onCompleteObservable.clear();
  8784. };
  8785. request.addEventListener("loadend", onLoadEnd);
  8786. var onReadyStateChange = function () {
  8787. if (aborted) {
  8788. return;
  8789. }
  8790. // In case of undefined state in some browsers.
  8791. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8792. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8793. request.removeEventListener("readystatechange", onReadyStateChange);
  8794. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8795. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8796. return;
  8797. }
  8798. var retryStrategy = Tools.DefaultRetryStrategy;
  8799. if (retryStrategy) {
  8800. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8801. if (waitTime !== -1) {
  8802. // Prevent the request from completing for retry.
  8803. request.removeEventListener("loadend", onLoadEnd);
  8804. request = new XMLHttpRequest();
  8805. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8806. return;
  8807. }
  8808. }
  8809. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8810. if (onError) {
  8811. onError(request, e);
  8812. }
  8813. else {
  8814. throw e;
  8815. }
  8816. }
  8817. };
  8818. request.addEventListener("readystatechange", onReadyStateChange);
  8819. request.send();
  8820. };
  8821. retryLoop(0);
  8822. };
  8823. // Caching all files
  8824. if (database && database.enableSceneOffline) {
  8825. var noIndexedDB_1 = function () {
  8826. if (!aborted) {
  8827. requestFile();
  8828. }
  8829. };
  8830. var loadFromIndexedDB = function () {
  8831. // TODO: database needs to support aborting and should return a IFileRequest
  8832. if (aborted) {
  8833. return;
  8834. }
  8835. if (database) {
  8836. database.loadFileFromDB(url, function (data) {
  8837. if (!aborted) {
  8838. onSuccess(data);
  8839. }
  8840. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8841. }, onProgress ? function (event) {
  8842. if (!aborted) {
  8843. onProgress(event);
  8844. }
  8845. } : undefined, noIndexedDB_1, useArrayBuffer);
  8846. }
  8847. };
  8848. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8849. }
  8850. else {
  8851. requestFile();
  8852. }
  8853. return fileRequest;
  8854. };
  8855. /**
  8856. * Load a script (identified by an url). When the url returns, the
  8857. * content of this file is added into a new script element, attached to the DOM (body element)
  8858. */
  8859. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8860. var head = document.getElementsByTagName('head')[0];
  8861. var script = document.createElement('script');
  8862. script.type = 'text/javascript';
  8863. script.src = scriptUrl;
  8864. script.onload = function () {
  8865. if (onSuccess) {
  8866. onSuccess();
  8867. }
  8868. };
  8869. script.onerror = function (e) {
  8870. if (onError) {
  8871. onError("Unable to load script '" + scriptUrl + "'", e);
  8872. }
  8873. };
  8874. head.appendChild(script);
  8875. };
  8876. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8877. var reader = new FileReader();
  8878. var request = {
  8879. onCompleteObservable: new BABYLON.Observable(),
  8880. abort: function () { return reader.abort(); },
  8881. };
  8882. reader.onloadend = function (e) {
  8883. request.onCompleteObservable.notifyObservers(request);
  8884. };
  8885. reader.onload = function (e) {
  8886. //target doesn't have result from ts 1.3
  8887. callback(e.target['result']);
  8888. };
  8889. reader.onprogress = progressCallback;
  8890. reader.readAsDataURL(fileToLoad);
  8891. return request;
  8892. };
  8893. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8894. var reader = new FileReader();
  8895. var request = {
  8896. onCompleteObservable: new BABYLON.Observable(),
  8897. abort: function () { return reader.abort(); },
  8898. };
  8899. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8900. reader.onerror = function (e) {
  8901. Tools.Log("Error while reading file: " + fileToLoad.name);
  8902. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8903. };
  8904. reader.onload = function (e) {
  8905. //target doesn't have result from ts 1.3
  8906. callback(e.target['result']);
  8907. };
  8908. if (progressCallBack) {
  8909. reader.onprogress = progressCallBack;
  8910. }
  8911. if (!useArrayBuffer) {
  8912. // Asynchronous read
  8913. reader.readAsText(fileToLoad);
  8914. }
  8915. else {
  8916. reader.readAsArrayBuffer(fileToLoad);
  8917. }
  8918. return request;
  8919. };
  8920. //returns a downloadable url to a file content.
  8921. Tools.FileAsURL = function (content) {
  8922. var fileBlob = new Blob([content]);
  8923. var url = window.URL || window.webkitURL;
  8924. var link = url.createObjectURL(fileBlob);
  8925. return link;
  8926. };
  8927. // Misc.
  8928. Tools.Format = function (value, decimals) {
  8929. if (decimals === void 0) { decimals = 2; }
  8930. return value.toFixed(decimals);
  8931. };
  8932. Tools.CheckExtends = function (v, min, max) {
  8933. if (v.x < min.x)
  8934. min.x = v.x;
  8935. if (v.y < min.y)
  8936. min.y = v.y;
  8937. if (v.z < min.z)
  8938. min.z = v.z;
  8939. if (v.x > max.x)
  8940. max.x = v.x;
  8941. if (v.y > max.y)
  8942. max.y = v.y;
  8943. if (v.z > max.z)
  8944. max.z = v.z;
  8945. };
  8946. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8947. for (var prop in source) {
  8948. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8949. continue;
  8950. }
  8951. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8952. continue;
  8953. }
  8954. var sourceValue = source[prop];
  8955. var typeOfSourceValue = typeof sourceValue;
  8956. if (typeOfSourceValue === "function") {
  8957. continue;
  8958. }
  8959. try {
  8960. if (typeOfSourceValue === "object") {
  8961. if (sourceValue instanceof Array) {
  8962. destination[prop] = [];
  8963. if (sourceValue.length > 0) {
  8964. if (typeof sourceValue[0] == "object") {
  8965. for (var index = 0; index < sourceValue.length; index++) {
  8966. var clonedValue = cloneValue(sourceValue[index], destination);
  8967. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  8968. destination[prop].push(clonedValue);
  8969. }
  8970. }
  8971. }
  8972. else {
  8973. destination[prop] = sourceValue.slice(0);
  8974. }
  8975. }
  8976. }
  8977. else {
  8978. destination[prop] = cloneValue(sourceValue, destination);
  8979. }
  8980. }
  8981. else {
  8982. destination[prop] = sourceValue;
  8983. }
  8984. }
  8985. catch (e) {
  8986. // Just ignore error (it could be because of a read-only property)
  8987. }
  8988. }
  8989. };
  8990. Tools.IsEmpty = function (obj) {
  8991. for (var i in obj) {
  8992. if (obj.hasOwnProperty(i)) {
  8993. return false;
  8994. }
  8995. }
  8996. return true;
  8997. };
  8998. Tools.RegisterTopRootEvents = function (events) {
  8999. for (var index = 0; index < events.length; index++) {
  9000. var event = events[index];
  9001. window.addEventListener(event.name, event.handler, false);
  9002. try {
  9003. if (window.parent) {
  9004. window.parent.addEventListener(event.name, event.handler, false);
  9005. }
  9006. }
  9007. catch (e) {
  9008. // Silently fails...
  9009. }
  9010. }
  9011. };
  9012. Tools.UnregisterTopRootEvents = function (events) {
  9013. for (var index = 0; index < events.length; index++) {
  9014. var event = events[index];
  9015. window.removeEventListener(event.name, event.handler);
  9016. try {
  9017. if (window.parent) {
  9018. window.parent.removeEventListener(event.name, event.handler);
  9019. }
  9020. }
  9021. catch (e) {
  9022. // Silently fails...
  9023. }
  9024. }
  9025. };
  9026. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9027. if (mimeType === void 0) { mimeType = "image/png"; }
  9028. // Read the contents of the framebuffer
  9029. var numberOfChannelsByLine = width * 4;
  9030. var halfHeight = height / 2;
  9031. //Reading datas from WebGL
  9032. var data = engine.readPixels(0, 0, width, height);
  9033. //To flip image on Y axis.
  9034. for (var i = 0; i < halfHeight; i++) {
  9035. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9036. var currentCell = j + i * numberOfChannelsByLine;
  9037. var targetLine = height - i - 1;
  9038. var targetCell = j + targetLine * numberOfChannelsByLine;
  9039. var temp = data[currentCell];
  9040. data[currentCell] = data[targetCell];
  9041. data[targetCell] = temp;
  9042. }
  9043. }
  9044. // Create a 2D canvas to store the result
  9045. if (!screenshotCanvas) {
  9046. screenshotCanvas = document.createElement('canvas');
  9047. }
  9048. screenshotCanvas.width = width;
  9049. screenshotCanvas.height = height;
  9050. var context = screenshotCanvas.getContext('2d');
  9051. if (context) {
  9052. // Copy the pixels to a 2D canvas
  9053. var imageData = context.createImageData(width, height);
  9054. var castData = (imageData.data);
  9055. castData.set(data);
  9056. context.putImageData(imageData, 0, 0);
  9057. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9058. }
  9059. };
  9060. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9061. if (mimeType === void 0) { mimeType = "image/png"; }
  9062. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9063. if (successCallback) {
  9064. successCallback(base64Image);
  9065. }
  9066. else {
  9067. // We need HTMLCanvasElement.toBlob for HD screenshots
  9068. if (!screenshotCanvas.toBlob) {
  9069. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9070. screenshotCanvas.toBlob = function (callback, type, quality) {
  9071. var _this = this;
  9072. setTimeout(function () {
  9073. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9074. for (var i = 0; i < len; i++) {
  9075. arr[i] = binStr.charCodeAt(i);
  9076. }
  9077. callback(new Blob([arr], { type: type || 'image/png' }));
  9078. });
  9079. };
  9080. }
  9081. screenshotCanvas.toBlob(function (blob) {
  9082. var url = URL.createObjectURL(blob);
  9083. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9084. if (("download" in document.createElement("a"))) {
  9085. var a = window.document.createElement("a");
  9086. a.href = url;
  9087. if (fileName) {
  9088. a.setAttribute("download", fileName);
  9089. }
  9090. else {
  9091. var date = new Date();
  9092. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9093. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9094. }
  9095. window.document.body.appendChild(a);
  9096. a.addEventListener("click", function () {
  9097. if (a.parentElement) {
  9098. a.parentElement.removeChild(a);
  9099. }
  9100. });
  9101. a.click();
  9102. }
  9103. else {
  9104. var newWindow = window.open("");
  9105. if (!newWindow)
  9106. return;
  9107. var img = newWindow.document.createElement("img");
  9108. img.onload = function () {
  9109. // no longer need to read the blob so it's revoked
  9110. URL.revokeObjectURL(url);
  9111. };
  9112. img.src = url;
  9113. newWindow.document.body.appendChild(img);
  9114. }
  9115. });
  9116. }
  9117. };
  9118. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9119. if (mimeType === void 0) { mimeType = "image/png"; }
  9120. var width;
  9121. var height;
  9122. // If a precision value is specified
  9123. if (size.precision) {
  9124. width = Math.round(engine.getRenderWidth() * size.precision);
  9125. height = Math.round(width / engine.getAspectRatio(camera));
  9126. }
  9127. else if (size.width && size.height) {
  9128. width = size.width;
  9129. height = size.height;
  9130. }
  9131. //If passing only width, computing height to keep display canvas ratio.
  9132. else if (size.width && !size.height) {
  9133. width = size.width;
  9134. height = Math.round(width / engine.getAspectRatio(camera));
  9135. }
  9136. //If passing only height, computing width to keep display canvas ratio.
  9137. else if (size.height && !size.width) {
  9138. height = size.height;
  9139. width = Math.round(height * engine.getAspectRatio(camera));
  9140. }
  9141. //Assuming here that "size" parameter is a number
  9142. else if (!isNaN(size)) {
  9143. height = size;
  9144. width = size;
  9145. }
  9146. else {
  9147. Tools.Error("Invalid 'size' parameter !");
  9148. return;
  9149. }
  9150. if (!screenshotCanvas) {
  9151. screenshotCanvas = document.createElement('canvas');
  9152. }
  9153. screenshotCanvas.width = width;
  9154. screenshotCanvas.height = height;
  9155. var renderContext = screenshotCanvas.getContext("2d");
  9156. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9157. var newWidth = width;
  9158. var newHeight = newWidth / ratio;
  9159. if (newHeight > height) {
  9160. newHeight = height;
  9161. newWidth = newHeight * ratio;
  9162. }
  9163. var offsetX = Math.max(0, width - newWidth) / 2;
  9164. var offsetY = Math.max(0, height - newHeight) / 2;
  9165. var renderingCanvas = engine.getRenderingCanvas();
  9166. if (renderContext && renderingCanvas) {
  9167. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9168. }
  9169. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9170. };
  9171. /**
  9172. * Generates an image screenshot from the specified camera.
  9173. *
  9174. * @param engine The engine to use for rendering
  9175. * @param camera The camera to use for rendering
  9176. * @param size This parameter can be set to a single number or to an object with the
  9177. * following (optional) properties: precision, width, height. If a single number is passed,
  9178. * it will be used for both width and height. If an object is passed, the screenshot size
  9179. * will be derived from the parameters. The precision property is a multiplier allowing
  9180. * rendering at a higher or lower resolution.
  9181. * @param successCallback The callback receives a single parameter which contains the
  9182. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9183. * src parameter of an <img> to display it.
  9184. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9185. * Check your browser for supported MIME types.
  9186. * @param samples Texture samples (default: 1)
  9187. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9188. * @param fileName A name for for the downloaded file.
  9189. * @constructor
  9190. */
  9191. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9192. if (mimeType === void 0) { mimeType = "image/png"; }
  9193. if (samples === void 0) { samples = 1; }
  9194. if (antialiasing === void 0) { antialiasing = false; }
  9195. var width;
  9196. var height;
  9197. //If a precision value is specified
  9198. if (size.precision) {
  9199. width = Math.round(engine.getRenderWidth() * size.precision);
  9200. height = Math.round(width / engine.getAspectRatio(camera));
  9201. size = { width: width, height: height };
  9202. }
  9203. else if (size.width && size.height) {
  9204. width = size.width;
  9205. height = size.height;
  9206. }
  9207. //If passing only width, computing height to keep display canvas ratio.
  9208. else if (size.width && !size.height) {
  9209. width = size.width;
  9210. height = Math.round(width / engine.getAspectRatio(camera));
  9211. size = { width: width, height: height };
  9212. }
  9213. //If passing only height, computing width to keep display canvas ratio.
  9214. else if (size.height && !size.width) {
  9215. height = size.height;
  9216. width = Math.round(height * engine.getAspectRatio(camera));
  9217. size = { width: width, height: height };
  9218. }
  9219. //Assuming here that "size" parameter is a number
  9220. else if (!isNaN(size)) {
  9221. height = size;
  9222. width = size;
  9223. }
  9224. else {
  9225. Tools.Error("Invalid 'size' parameter !");
  9226. return;
  9227. }
  9228. var scene = camera.getScene();
  9229. var previousCamera = null;
  9230. if (scene.activeCamera !== camera) {
  9231. previousCamera = scene.activeCamera;
  9232. scene.activeCamera = camera;
  9233. }
  9234. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9235. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9236. texture.renderList = null;
  9237. texture.samples = samples;
  9238. if (antialiasing) {
  9239. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9240. }
  9241. texture.onAfterRenderObservable.add(function () {
  9242. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9243. });
  9244. scene.incrementRenderId();
  9245. scene.resetCachedMaterial();
  9246. texture.render(true);
  9247. texture.dispose();
  9248. if (previousCamera) {
  9249. scene.activeCamera = previousCamera;
  9250. }
  9251. camera.getProjectionMatrix(true); // Force cache refresh;
  9252. };
  9253. // XHR response validator for local file scenario
  9254. Tools.ValidateXHRData = function (xhr, dataType) {
  9255. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9256. if (dataType === void 0) { dataType = 7; }
  9257. try {
  9258. if (dataType & 1) {
  9259. if (xhr.responseText && xhr.responseText.length > 0) {
  9260. return true;
  9261. }
  9262. else if (dataType === 1) {
  9263. return false;
  9264. }
  9265. }
  9266. if (dataType & 2) {
  9267. // Check header width and height since there is no "TGA" magic number
  9268. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9269. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9270. return true;
  9271. }
  9272. else if (dataType === 2) {
  9273. return false;
  9274. }
  9275. }
  9276. if (dataType & 4) {
  9277. // Check for the "DDS" magic number
  9278. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9279. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9280. return true;
  9281. }
  9282. else {
  9283. return false;
  9284. }
  9285. }
  9286. }
  9287. catch (e) {
  9288. // Global protection
  9289. }
  9290. return false;
  9291. };
  9292. /**
  9293. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9294. * Be aware Math.random() could cause collisions, but:
  9295. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9296. */
  9297. Tools.RandomId = function () {
  9298. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9299. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9300. return v.toString(16);
  9301. });
  9302. };
  9303. /**
  9304. * Test if the given uri is a base64 string.
  9305. * @param uri The uri to test
  9306. * @return True if the uri is a base64 string or false otherwise.
  9307. */
  9308. Tools.IsBase64 = function (uri) {
  9309. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9310. };
  9311. /**
  9312. * Decode the given base64 uri.
  9313. * @param uri The uri to decode
  9314. * @return The decoded base64 data.
  9315. */
  9316. Tools.DecodeBase64 = function (uri) {
  9317. var decodedString = atob(uri.split(",")[1]);
  9318. var bufferLength = decodedString.length;
  9319. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9320. for (var i = 0; i < bufferLength; i++) {
  9321. bufferView[i] = decodedString.charCodeAt(i);
  9322. }
  9323. return bufferView.buffer;
  9324. };
  9325. Object.defineProperty(Tools, "NoneLogLevel", {
  9326. get: function () {
  9327. return Tools._NoneLogLevel;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(Tools, "MessageLogLevel", {
  9333. get: function () {
  9334. return Tools._MessageLogLevel;
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Object.defineProperty(Tools, "WarningLogLevel", {
  9340. get: function () {
  9341. return Tools._WarningLogLevel;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Object.defineProperty(Tools, "ErrorLogLevel", {
  9347. get: function () {
  9348. return Tools._ErrorLogLevel;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(Tools, "AllLogLevel", {
  9354. get: function () {
  9355. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Tools._AddLogEntry = function (entry) {
  9361. Tools._LogCache = entry + Tools._LogCache;
  9362. if (Tools.OnNewCacheEntry) {
  9363. Tools.OnNewCacheEntry(entry);
  9364. }
  9365. };
  9366. Tools._FormatMessage = function (message) {
  9367. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9368. var date = new Date();
  9369. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9370. };
  9371. Tools._LogDisabled = function (message) {
  9372. // nothing to do
  9373. };
  9374. Tools._LogEnabled = function (message) {
  9375. var formattedMessage = Tools._FormatMessage(message);
  9376. console.log("BJS - " + formattedMessage);
  9377. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9378. Tools._AddLogEntry(entry);
  9379. };
  9380. Tools._WarnDisabled = function (message) {
  9381. // nothing to do
  9382. };
  9383. Tools._WarnEnabled = function (message) {
  9384. var formattedMessage = Tools._FormatMessage(message);
  9385. console.warn("BJS - " + formattedMessage);
  9386. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9387. Tools._AddLogEntry(entry);
  9388. };
  9389. Tools._ErrorDisabled = function (message) {
  9390. // nothing to do
  9391. };
  9392. Tools._ErrorEnabled = function (message) {
  9393. Tools.errorsCount++;
  9394. var formattedMessage = Tools._FormatMessage(message);
  9395. console.error("BJS - " + formattedMessage);
  9396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9397. Tools._AddLogEntry(entry);
  9398. };
  9399. Object.defineProperty(Tools, "LogCache", {
  9400. get: function () {
  9401. return Tools._LogCache;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Tools.ClearLogCache = function () {
  9407. Tools._LogCache = "";
  9408. Tools.errorsCount = 0;
  9409. };
  9410. Object.defineProperty(Tools, "LogLevels", {
  9411. set: function (level) {
  9412. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9413. Tools.Log = Tools._LogEnabled;
  9414. }
  9415. else {
  9416. Tools.Log = Tools._LogDisabled;
  9417. }
  9418. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9419. Tools.Warn = Tools._WarnEnabled;
  9420. }
  9421. else {
  9422. Tools.Warn = Tools._WarnDisabled;
  9423. }
  9424. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9425. Tools.Error = Tools._ErrorEnabled;
  9426. }
  9427. else {
  9428. Tools.Error = Tools._ErrorDisabled;
  9429. }
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Tools.IsWindowObjectExist = function () {
  9435. return (typeof window) !== "undefined";
  9436. };
  9437. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9438. get: function () {
  9439. return Tools._PerformanceNoneLogLevel;
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9445. get: function () {
  9446. return Tools._PerformanceUserMarkLogLevel;
  9447. },
  9448. enumerable: true,
  9449. configurable: true
  9450. });
  9451. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9452. get: function () {
  9453. return Tools._PerformanceConsoleLogLevel;
  9454. },
  9455. enumerable: true,
  9456. configurable: true
  9457. });
  9458. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9459. set: function (level) {
  9460. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9461. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9462. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9463. return;
  9464. }
  9465. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9466. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9467. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9468. return;
  9469. }
  9470. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9471. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9477. };
  9478. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9479. };
  9480. Tools._StartUserMark = function (counterName, condition) {
  9481. if (condition === void 0) { condition = true; }
  9482. if (!Tools._performance) {
  9483. if (!Tools.IsWindowObjectExist()) {
  9484. return;
  9485. }
  9486. Tools._performance = window.performance;
  9487. }
  9488. if (!condition || !Tools._performance.mark) {
  9489. return;
  9490. }
  9491. Tools._performance.mark(counterName + "-Begin");
  9492. };
  9493. Tools._EndUserMark = function (counterName, condition) {
  9494. if (condition === void 0) { condition = true; }
  9495. if (!condition || !Tools._performance.mark) {
  9496. return;
  9497. }
  9498. Tools._performance.mark(counterName + "-End");
  9499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9500. };
  9501. Tools._StartPerformanceConsole = function (counterName, condition) {
  9502. if (condition === void 0) { condition = true; }
  9503. if (!condition) {
  9504. return;
  9505. }
  9506. Tools._StartUserMark(counterName, condition);
  9507. if (console.time) {
  9508. console.time(counterName);
  9509. }
  9510. };
  9511. Tools._EndPerformanceConsole = function (counterName, condition) {
  9512. if (condition === void 0) { condition = true; }
  9513. if (!condition) {
  9514. return;
  9515. }
  9516. Tools._EndUserMark(counterName, condition);
  9517. if (console.time) {
  9518. console.timeEnd(counterName);
  9519. }
  9520. };
  9521. Object.defineProperty(Tools, "Now", {
  9522. get: function () {
  9523. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9524. return window.performance.now();
  9525. }
  9526. return Date.now();
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. /**
  9532. * This method will return the name of the class used to create the instance of the given object.
  9533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9534. * @param object the object to get the class name from
  9535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9536. */
  9537. Tools.GetClassName = function (object, isType) {
  9538. if (isType === void 0) { isType = false; }
  9539. var name = null;
  9540. if (!isType && object.getClassName) {
  9541. name = object.getClassName();
  9542. }
  9543. else {
  9544. if (object instanceof Object) {
  9545. var classObj = isType ? object : Object.getPrototypeOf(object);
  9546. name = classObj.constructor["__bjsclassName__"];
  9547. }
  9548. if (!name) {
  9549. name = typeof object;
  9550. }
  9551. }
  9552. return name;
  9553. };
  9554. Tools.First = function (array, predicate) {
  9555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9556. var el = array_1[_i];
  9557. if (predicate(el)) {
  9558. return el;
  9559. }
  9560. }
  9561. return null;
  9562. };
  9563. /**
  9564. * This method will return the name of the full name of the class, including its owning module (if any).
  9565. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9566. * @param object the object to get the class name from
  9567. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9568. */
  9569. Tools.getFullClassName = function (object, isType) {
  9570. if (isType === void 0) { isType = false; }
  9571. var className = null;
  9572. var moduleName = null;
  9573. if (!isType && object.getClassName) {
  9574. className = object.getClassName();
  9575. }
  9576. else {
  9577. if (object instanceof Object) {
  9578. var classObj = isType ? object : Object.getPrototypeOf(object);
  9579. className = classObj.constructor["__bjsclassName__"];
  9580. moduleName = classObj.constructor["__bjsmoduleName__"];
  9581. }
  9582. if (!className) {
  9583. className = typeof object;
  9584. }
  9585. }
  9586. if (!className) {
  9587. return null;
  9588. }
  9589. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9590. };
  9591. /**
  9592. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9593. * @param array
  9594. */
  9595. Tools.arrayOrStringFeeder = function (array) {
  9596. return function (index) {
  9597. if (index >= array.length) {
  9598. return null;
  9599. }
  9600. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9601. if (val && val.getHashCode) {
  9602. val = val.getHashCode();
  9603. }
  9604. if (typeof val === "string") {
  9605. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9606. }
  9607. return val;
  9608. };
  9609. };
  9610. /**
  9611. * Compute the hashCode of a stream of number
  9612. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9613. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9614. * @return the hash code computed
  9615. */
  9616. Tools.hashCodeFromStream = function (feeder) {
  9617. // Based from here: http://stackoverflow.com/a/7616484/802124
  9618. var hash = 0;
  9619. var index = 0;
  9620. var chr = feeder(index++);
  9621. while (chr != null) {
  9622. hash = ((hash << 5) - hash) + chr;
  9623. hash |= 0; // Convert to 32bit integer
  9624. chr = feeder(index++);
  9625. }
  9626. return hash;
  9627. };
  9628. /**
  9629. * Returns a promise that resolves after the given amount of time.
  9630. * @param delay Number of milliseconds to delay
  9631. * @returns Promise that resolves after the given amount of time
  9632. */
  9633. Tools.DelayAsync = function (delay) {
  9634. return new Promise(function (resolve) {
  9635. setTimeout(function () {
  9636. resolve();
  9637. }, delay);
  9638. });
  9639. };
  9640. Tools.BaseUrl = "";
  9641. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9642. /**
  9643. * Default behaviour for cors in the application.
  9644. * It can be a string if the expected behavior is identical in the entire app.
  9645. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9646. */
  9647. Tools.CorsBehavior = "anonymous";
  9648. Tools.UseFallbackTexture = true;
  9649. /**
  9650. * Use this object to register external classes like custom textures or material
  9651. * to allow the laoders to instantiate them
  9652. */
  9653. Tools.RegisteredExternalClasses = {};
  9654. // Used in case of a texture loading problem
  9655. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9656. Tools.PreprocessUrl = function (url) {
  9657. return url;
  9658. };
  9659. // Logs
  9660. Tools._NoneLogLevel = 0;
  9661. Tools._MessageLogLevel = 1;
  9662. Tools._WarningLogLevel = 2;
  9663. Tools._ErrorLogLevel = 4;
  9664. Tools._LogCache = "";
  9665. Tools.errorsCount = 0;
  9666. Tools.Log = Tools._LogEnabled;
  9667. Tools.Warn = Tools._WarnEnabled;
  9668. Tools.Error = Tools._ErrorEnabled;
  9669. // Performances
  9670. Tools._PerformanceNoneLogLevel = 0;
  9671. Tools._PerformanceUserMarkLogLevel = 1;
  9672. Tools._PerformanceConsoleLogLevel = 2;
  9673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9675. return Tools;
  9676. }());
  9677. BABYLON.Tools = Tools;
  9678. /**
  9679. * This class is used to track a performance counter which is number based.
  9680. * The user has access to many properties which give statistics of different nature
  9681. *
  9682. * The implementer can track two kinds of Performance Counter: time and count
  9683. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9684. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9685. */
  9686. var PerfCounter = /** @class */ (function () {
  9687. function PerfCounter() {
  9688. this._startMonitoringTime = 0;
  9689. this._min = 0;
  9690. this._max = 0;
  9691. this._average = 0;
  9692. this._lastSecAverage = 0;
  9693. this._current = 0;
  9694. this._totalValueCount = 0;
  9695. this._totalAccumulated = 0;
  9696. this._lastSecAccumulated = 0;
  9697. this._lastSecTime = 0;
  9698. this._lastSecValueCount = 0;
  9699. }
  9700. Object.defineProperty(PerfCounter.prototype, "min", {
  9701. /**
  9702. * Returns the smallest value ever
  9703. */
  9704. get: function () {
  9705. return this._min;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(PerfCounter.prototype, "max", {
  9711. /**
  9712. * Returns the biggest value ever
  9713. */
  9714. get: function () {
  9715. return this._max;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(PerfCounter.prototype, "average", {
  9721. /**
  9722. * Returns the average value since the performance counter is running
  9723. */
  9724. get: function () {
  9725. return this._average;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9731. /**
  9732. * Returns the average value of the last second the counter was monitored
  9733. */
  9734. get: function () {
  9735. return this._lastSecAverage;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(PerfCounter.prototype, "current", {
  9741. /**
  9742. * Returns the current value
  9743. */
  9744. get: function () {
  9745. return this._current;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(PerfCounter.prototype, "total", {
  9751. get: function () {
  9752. return this._totalAccumulated;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(PerfCounter.prototype, "count", {
  9758. get: function () {
  9759. return this._totalValueCount;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. /**
  9765. * Call this method to start monitoring a new frame.
  9766. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9767. */
  9768. PerfCounter.prototype.fetchNewFrame = function () {
  9769. this._totalValueCount++;
  9770. this._current = 0;
  9771. this._lastSecValueCount++;
  9772. };
  9773. /**
  9774. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9775. * @param newCount the count value to add to the monitored count
  9776. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9777. */
  9778. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9779. if (!PerfCounter.Enabled) {
  9780. return;
  9781. }
  9782. this._current += newCount;
  9783. if (fetchResult) {
  9784. this._fetchResult();
  9785. }
  9786. };
  9787. /**
  9788. * Start monitoring this performance counter
  9789. */
  9790. PerfCounter.prototype.beginMonitoring = function () {
  9791. if (!PerfCounter.Enabled) {
  9792. return;
  9793. }
  9794. this._startMonitoringTime = Tools.Now;
  9795. };
  9796. /**
  9797. * Compute the time lapsed since the previous beginMonitoring() call.
  9798. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9799. */
  9800. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9801. if (newFrame === void 0) { newFrame = true; }
  9802. if (!PerfCounter.Enabled) {
  9803. return;
  9804. }
  9805. if (newFrame) {
  9806. this.fetchNewFrame();
  9807. }
  9808. var currentTime = Tools.Now;
  9809. this._current = currentTime - this._startMonitoringTime;
  9810. if (newFrame) {
  9811. this._fetchResult();
  9812. }
  9813. };
  9814. PerfCounter.prototype._fetchResult = function () {
  9815. this._totalAccumulated += this._current;
  9816. this._lastSecAccumulated += this._current;
  9817. // Min/Max update
  9818. this._min = Math.min(this._min, this._current);
  9819. this._max = Math.max(this._max, this._current);
  9820. this._average = this._totalAccumulated / this._totalValueCount;
  9821. // Reset last sec?
  9822. var now = Tools.Now;
  9823. if ((now - this._lastSecTime) > 1000) {
  9824. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9825. this._lastSecTime = now;
  9826. this._lastSecAccumulated = 0;
  9827. this._lastSecValueCount = 0;
  9828. }
  9829. };
  9830. PerfCounter.Enabled = true;
  9831. return PerfCounter;
  9832. }());
  9833. BABYLON.PerfCounter = PerfCounter;
  9834. /**
  9835. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9836. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9837. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9838. * @param name The name of the class, case should be preserved
  9839. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9840. */
  9841. function className(name, module) {
  9842. return function (target) {
  9843. target["__bjsclassName__"] = name;
  9844. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9845. };
  9846. }
  9847. BABYLON.className = className;
  9848. /**
  9849. * An implementation of a loop for asynchronous functions.
  9850. */
  9851. var AsyncLoop = /** @class */ (function () {
  9852. /**
  9853. * Constroctor.
  9854. * @param iterations the number of iterations.
  9855. * @param _fn the function to run each iteration
  9856. * @param _successCallback the callback that will be called upon succesful execution
  9857. * @param offset starting offset.
  9858. */
  9859. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9860. if (offset === void 0) { offset = 0; }
  9861. this.iterations = iterations;
  9862. this._fn = _fn;
  9863. this._successCallback = _successCallback;
  9864. this.index = offset - 1;
  9865. this._done = false;
  9866. }
  9867. /**
  9868. * Execute the next iteration. Must be called after the last iteration was finished.
  9869. */
  9870. AsyncLoop.prototype.executeNext = function () {
  9871. if (!this._done) {
  9872. if (this.index + 1 < this.iterations) {
  9873. ++this.index;
  9874. this._fn(this);
  9875. }
  9876. else {
  9877. this.breakLoop();
  9878. }
  9879. }
  9880. };
  9881. /**
  9882. * Break the loop and run the success callback.
  9883. */
  9884. AsyncLoop.prototype.breakLoop = function () {
  9885. this._done = true;
  9886. this._successCallback();
  9887. };
  9888. /**
  9889. * Helper function
  9890. */
  9891. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9892. if (offset === void 0) { offset = 0; }
  9893. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9894. loop.executeNext();
  9895. return loop;
  9896. };
  9897. /**
  9898. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9899. * @param iterations total number of iterations
  9900. * @param syncedIterations number of synchronous iterations in each async iteration.
  9901. * @param fn the function to call each iteration.
  9902. * @param callback a success call back that will be called when iterating stops.
  9903. * @param breakFunction a break condition (optional)
  9904. * @param timeout timeout settings for the setTimeout function. default - 0.
  9905. * @constructor
  9906. */
  9907. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9908. if (timeout === void 0) { timeout = 0; }
  9909. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9910. if (breakFunction && breakFunction())
  9911. loop.breakLoop();
  9912. else {
  9913. setTimeout(function () {
  9914. for (var i = 0; i < syncedIterations; ++i) {
  9915. var iteration = (loop.index * syncedIterations) + i;
  9916. if (iteration >= iterations)
  9917. break;
  9918. fn(iteration);
  9919. if (breakFunction && breakFunction()) {
  9920. loop.breakLoop();
  9921. break;
  9922. }
  9923. }
  9924. loop.executeNext();
  9925. }, timeout);
  9926. }
  9927. }, callback);
  9928. };
  9929. return AsyncLoop;
  9930. }());
  9931. BABYLON.AsyncLoop = AsyncLoop;
  9932. })(BABYLON || (BABYLON = {}));
  9933. //# sourceMappingURL=babylon.tools.js.map
  9934. var BABYLON;
  9935. (function (BABYLON) {
  9936. var PromiseStates;
  9937. (function (PromiseStates) {
  9938. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9939. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9940. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9941. })(PromiseStates || (PromiseStates = {}));
  9942. var FulFillmentAgregator = /** @class */ (function () {
  9943. function FulFillmentAgregator() {
  9944. this.count = 0;
  9945. this.target = 0;
  9946. this.results = [];
  9947. }
  9948. return FulFillmentAgregator;
  9949. }());
  9950. var InternalPromise = /** @class */ (function () {
  9951. function InternalPromise(resolver) {
  9952. var _this = this;
  9953. this._state = PromiseStates.Pending;
  9954. this._children = new Array();
  9955. this._rejectWasConsumed = false;
  9956. if (!resolver) {
  9957. return;
  9958. }
  9959. try {
  9960. resolver(function (value) {
  9961. _this._resolve(value);
  9962. }, function (reason) {
  9963. _this._reject(reason);
  9964. });
  9965. }
  9966. catch (e) {
  9967. this._reject(e);
  9968. }
  9969. }
  9970. InternalPromise.prototype.catch = function (onRejected) {
  9971. return this.then(undefined, onRejected);
  9972. };
  9973. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9974. var _this = this;
  9975. var newPromise = new InternalPromise();
  9976. newPromise._onFulfilled = onFulfilled;
  9977. newPromise._onRejected = onRejected;
  9978. // Composition
  9979. this._children.push(newPromise);
  9980. if (this._state !== PromiseStates.Pending) {
  9981. BABYLON.Tools.SetImmediate(function () {
  9982. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9983. var returnedValue = newPromise._resolve(_this._result);
  9984. if (returnedValue !== undefined && returnedValue !== null) {
  9985. if (returnedValue._state !== undefined) {
  9986. var returnedPromise = returnedValue;
  9987. newPromise._children.push(returnedPromise);
  9988. newPromise = returnedPromise;
  9989. }
  9990. else {
  9991. newPromise._result = returnedValue;
  9992. }
  9993. }
  9994. }
  9995. else {
  9996. newPromise._reject(_this._reason);
  9997. }
  9998. });
  9999. }
  10000. return newPromise;
  10001. };
  10002. InternalPromise.prototype._moveChildren = function (children) {
  10003. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10004. if (this._state === PromiseStates.Fulfilled) {
  10005. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10006. var child = _b[_i];
  10007. child._resolve(this._result);
  10008. }
  10009. }
  10010. else if (this._state === PromiseStates.Rejected) {
  10011. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10012. var child = _d[_c];
  10013. child._reject(this._reason);
  10014. }
  10015. }
  10016. var _a;
  10017. };
  10018. InternalPromise.prototype._resolve = function (value) {
  10019. try {
  10020. this._state = PromiseStates.Fulfilled;
  10021. var returnedValue = null;
  10022. if (this._onFulfilled) {
  10023. returnedValue = this._onFulfilled(value);
  10024. }
  10025. if (returnedValue !== undefined && returnedValue !== null) {
  10026. if (returnedValue._state !== undefined) {
  10027. // Transmit children
  10028. var returnedPromise = returnedValue;
  10029. returnedPromise._moveChildren(this._children);
  10030. value = returnedPromise._result;
  10031. }
  10032. else {
  10033. value = returnedValue;
  10034. }
  10035. }
  10036. this._result = value;
  10037. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10038. var child = _a[_i];
  10039. child._resolve(value);
  10040. }
  10041. this._children.length = 0;
  10042. delete this._onFulfilled;
  10043. delete this._onRejected;
  10044. }
  10045. catch (e) {
  10046. this._reject(e, true);
  10047. }
  10048. };
  10049. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10050. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10051. this._state = PromiseStates.Rejected;
  10052. this._reason = reason;
  10053. if (this._onRejected && !onLocalThrow) {
  10054. try {
  10055. this._onRejected(reason);
  10056. this._rejectWasConsumed = true;
  10057. }
  10058. catch (e) {
  10059. reason = e;
  10060. }
  10061. }
  10062. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10063. var child = _a[_i];
  10064. if (this._rejectWasConsumed) {
  10065. child._resolve(null);
  10066. }
  10067. else {
  10068. child._reject(reason);
  10069. }
  10070. }
  10071. this._children.length = 0;
  10072. delete this._onFulfilled;
  10073. delete this._onRejected;
  10074. };
  10075. InternalPromise.resolve = function (value) {
  10076. var newPromise = new InternalPromise();
  10077. newPromise._resolve(value);
  10078. return newPromise;
  10079. };
  10080. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10081. promise.then(function (value) {
  10082. agregator.results[index] = value;
  10083. agregator.count++;
  10084. if (agregator.count === agregator.target) {
  10085. agregator.rootPromise._resolve(agregator.results);
  10086. }
  10087. return null;
  10088. }, function (reason) {
  10089. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10090. agregator.rootPromise._reject(reason);
  10091. }
  10092. });
  10093. };
  10094. InternalPromise.all = function (promises) {
  10095. var newPromise = new InternalPromise();
  10096. var agregator = new FulFillmentAgregator();
  10097. agregator.target = promises.length;
  10098. agregator.rootPromise = newPromise;
  10099. if (promises.length) {
  10100. for (var index = 0; index < promises.length; index++) {
  10101. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10102. }
  10103. }
  10104. else {
  10105. newPromise._resolve([]);
  10106. }
  10107. return newPromise;
  10108. };
  10109. InternalPromise.race = function (promises) {
  10110. var newPromise = new InternalPromise();
  10111. if (promises.length) {
  10112. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10113. var promise = promises_1[_i];
  10114. promise.then(function (value) {
  10115. if (newPromise) {
  10116. newPromise._resolve(value);
  10117. newPromise = null;
  10118. }
  10119. return null;
  10120. }, function (reason) {
  10121. if (newPromise) {
  10122. newPromise._reject(reason);
  10123. newPromise = null;
  10124. }
  10125. });
  10126. }
  10127. }
  10128. return newPromise;
  10129. };
  10130. return InternalPromise;
  10131. }());
  10132. /**
  10133. * Helper class that provides a small promise polyfill
  10134. */
  10135. var PromisePolyfill = /** @class */ (function () {
  10136. function PromisePolyfill() {
  10137. }
  10138. /**
  10139. * Static function used to check if the polyfill is required
  10140. * If this is the case then the function will inject the polyfill to window.Promise
  10141. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10142. */
  10143. PromisePolyfill.Apply = function (force) {
  10144. if (force === void 0) { force = false; }
  10145. if (force || typeof Promise === 'undefined') {
  10146. var root = window;
  10147. root.Promise = InternalPromise;
  10148. }
  10149. };
  10150. return PromisePolyfill;
  10151. }());
  10152. BABYLON.PromisePolyfill = PromisePolyfill;
  10153. })(BABYLON || (BABYLON = {}));
  10154. //# sourceMappingURL=babylon.promise.js.map
  10155. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10156. var BABYLON;
  10157. (function (BABYLON) {
  10158. /**
  10159. * Helper class to push actions to a pool of workers.
  10160. */
  10161. var WorkerPool = /** @class */ (function () {
  10162. /**
  10163. * Constructor
  10164. * @param workers Array of workers to use for actions
  10165. */
  10166. function WorkerPool(workers) {
  10167. this._pendingActions = new Array();
  10168. this._workerInfos = workers.map(function (worker) { return ({
  10169. worker: worker,
  10170. active: false
  10171. }); });
  10172. }
  10173. /**
  10174. * Terminates all workers and clears any pending actions.
  10175. */
  10176. WorkerPool.prototype.dispose = function () {
  10177. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10178. var workerInfo = _a[_i];
  10179. workerInfo.worker.terminate();
  10180. }
  10181. delete this._workerInfos;
  10182. delete this._pendingActions;
  10183. };
  10184. /**
  10185. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10186. * pended until a worker has completed its action.
  10187. * @param action The action to perform. Call onComplete when the action is complete.
  10188. */
  10189. WorkerPool.prototype.push = function (action) {
  10190. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10191. var workerInfo = _a[_i];
  10192. if (!workerInfo.active) {
  10193. this._execute(workerInfo, action);
  10194. return;
  10195. }
  10196. }
  10197. this._pendingActions.push(action);
  10198. };
  10199. WorkerPool.prototype._execute = function (workerInfo, action) {
  10200. var _this = this;
  10201. workerInfo.active = true;
  10202. action(workerInfo.worker, function () {
  10203. workerInfo.active = false;
  10204. var nextAction = _this._pendingActions.shift();
  10205. if (nextAction) {
  10206. _this._execute(workerInfo, nextAction);
  10207. }
  10208. });
  10209. };
  10210. return WorkerPool;
  10211. }());
  10212. BABYLON.WorkerPool = WorkerPool;
  10213. })(BABYLON || (BABYLON = {}));
  10214. //# sourceMappingURL=babylon.workerPool.js.map
  10215. var BABYLON;
  10216. (function (BABYLON) {
  10217. var _AlphaState = /** @class */ (function () {
  10218. /**
  10219. * Initializes the state.
  10220. */
  10221. function _AlphaState() {
  10222. this._isAlphaBlendDirty = false;
  10223. this._isBlendFunctionParametersDirty = false;
  10224. this._isBlendEquationParametersDirty = false;
  10225. this._isBlendConstantsDirty = false;
  10226. this._alphaBlend = false;
  10227. this._blendFunctionParameters = new Array(4);
  10228. this._blendEquationParameters = new Array(2);
  10229. this._blendConstants = new Array(4);
  10230. this.reset();
  10231. }
  10232. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10233. get: function () {
  10234. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10240. get: function () {
  10241. return this._alphaBlend;
  10242. },
  10243. set: function (value) {
  10244. if (this._alphaBlend === value) {
  10245. return;
  10246. }
  10247. this._alphaBlend = value;
  10248. this._isAlphaBlendDirty = true;
  10249. },
  10250. enumerable: true,
  10251. configurable: true
  10252. });
  10253. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10254. if (this._blendConstants[0] === r &&
  10255. this._blendConstants[1] === g &&
  10256. this._blendConstants[2] === b &&
  10257. this._blendConstants[3] === a) {
  10258. return;
  10259. }
  10260. this._blendConstants[0] = r;
  10261. this._blendConstants[1] = g;
  10262. this._blendConstants[2] = b;
  10263. this._blendConstants[3] = a;
  10264. this._isBlendConstantsDirty = true;
  10265. };
  10266. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10267. if (this._blendFunctionParameters[0] === value0 &&
  10268. this._blendFunctionParameters[1] === value1 &&
  10269. this._blendFunctionParameters[2] === value2 &&
  10270. this._blendFunctionParameters[3] === value3) {
  10271. return;
  10272. }
  10273. this._blendFunctionParameters[0] = value0;
  10274. this._blendFunctionParameters[1] = value1;
  10275. this._blendFunctionParameters[2] = value2;
  10276. this._blendFunctionParameters[3] = value3;
  10277. this._isBlendFunctionParametersDirty = true;
  10278. };
  10279. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10280. if (this._blendEquationParameters[0] === rgb &&
  10281. this._blendEquationParameters[1] === alpha) {
  10282. return;
  10283. }
  10284. this._blendEquationParameters[0] = rgb;
  10285. this._blendEquationParameters[1] = alpha;
  10286. this._isBlendEquationParametersDirty = true;
  10287. };
  10288. _AlphaState.prototype.reset = function () {
  10289. this._alphaBlend = false;
  10290. this._blendFunctionParameters[0] = null;
  10291. this._blendFunctionParameters[1] = null;
  10292. this._blendFunctionParameters[2] = null;
  10293. this._blendFunctionParameters[3] = null;
  10294. this._blendEquationParameters[0] = null;
  10295. this._blendEquationParameters[1] = null;
  10296. this._blendConstants[0] = null;
  10297. this._blendConstants[1] = null;
  10298. this._blendConstants[2] = null;
  10299. this._blendConstants[3] = null;
  10300. this._isAlphaBlendDirty = true;
  10301. this._isBlendFunctionParametersDirty = false;
  10302. this._isBlendEquationParametersDirty = false;
  10303. this._isBlendConstantsDirty = false;
  10304. };
  10305. _AlphaState.prototype.apply = function (gl) {
  10306. if (!this.isDirty) {
  10307. return;
  10308. }
  10309. // Alpha blend
  10310. if (this._isAlphaBlendDirty) {
  10311. if (this._alphaBlend) {
  10312. gl.enable(gl.BLEND);
  10313. }
  10314. else {
  10315. gl.disable(gl.BLEND);
  10316. }
  10317. this._isAlphaBlendDirty = false;
  10318. }
  10319. // Alpha function
  10320. if (this._isBlendFunctionParametersDirty) {
  10321. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10322. this._isBlendFunctionParametersDirty = false;
  10323. }
  10324. // Alpha equation
  10325. if (this._isBlendEquationParametersDirty) {
  10326. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10327. this._isBlendEquationParametersDirty = false;
  10328. }
  10329. // Constants
  10330. if (this._isBlendConstantsDirty) {
  10331. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10332. this._isBlendConstantsDirty = false;
  10333. }
  10334. };
  10335. return _AlphaState;
  10336. }());
  10337. BABYLON._AlphaState = _AlphaState;
  10338. })(BABYLON || (BABYLON = {}));
  10339. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10340. var BABYLON;
  10341. (function (BABYLON) {
  10342. var _DepthCullingState = /** @class */ (function () {
  10343. /**
  10344. * Initializes the state.
  10345. */
  10346. function _DepthCullingState() {
  10347. this._isDepthTestDirty = false;
  10348. this._isDepthMaskDirty = false;
  10349. this._isDepthFuncDirty = false;
  10350. this._isCullFaceDirty = false;
  10351. this._isCullDirty = false;
  10352. this._isZOffsetDirty = false;
  10353. this._isFrontFaceDirty = false;
  10354. this.reset();
  10355. }
  10356. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10357. get: function () {
  10358. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10359. },
  10360. enumerable: true,
  10361. configurable: true
  10362. });
  10363. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10364. get: function () {
  10365. return this._zOffset;
  10366. },
  10367. set: function (value) {
  10368. if (this._zOffset === value) {
  10369. return;
  10370. }
  10371. this._zOffset = value;
  10372. this._isZOffsetDirty = true;
  10373. },
  10374. enumerable: true,
  10375. configurable: true
  10376. });
  10377. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10378. get: function () {
  10379. return this._cullFace;
  10380. },
  10381. set: function (value) {
  10382. if (this._cullFace === value) {
  10383. return;
  10384. }
  10385. this._cullFace = value;
  10386. this._isCullFaceDirty = true;
  10387. },
  10388. enumerable: true,
  10389. configurable: true
  10390. });
  10391. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10392. get: function () {
  10393. return this._cull;
  10394. },
  10395. set: function (value) {
  10396. if (this._cull === value) {
  10397. return;
  10398. }
  10399. this._cull = value;
  10400. this._isCullDirty = true;
  10401. },
  10402. enumerable: true,
  10403. configurable: true
  10404. });
  10405. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10406. get: function () {
  10407. return this._depthFunc;
  10408. },
  10409. set: function (value) {
  10410. if (this._depthFunc === value) {
  10411. return;
  10412. }
  10413. this._depthFunc = value;
  10414. this._isDepthFuncDirty = true;
  10415. },
  10416. enumerable: true,
  10417. configurable: true
  10418. });
  10419. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10420. get: function () {
  10421. return this._depthMask;
  10422. },
  10423. set: function (value) {
  10424. if (this._depthMask === value) {
  10425. return;
  10426. }
  10427. this._depthMask = value;
  10428. this._isDepthMaskDirty = true;
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10434. get: function () {
  10435. return this._depthTest;
  10436. },
  10437. set: function (value) {
  10438. if (this._depthTest === value) {
  10439. return;
  10440. }
  10441. this._depthTest = value;
  10442. this._isDepthTestDirty = true;
  10443. },
  10444. enumerable: true,
  10445. configurable: true
  10446. });
  10447. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10448. get: function () {
  10449. return this._frontFace;
  10450. },
  10451. set: function (value) {
  10452. if (this._frontFace === value) {
  10453. return;
  10454. }
  10455. this._frontFace = value;
  10456. this._isFrontFaceDirty = true;
  10457. },
  10458. enumerable: true,
  10459. configurable: true
  10460. });
  10461. _DepthCullingState.prototype.reset = function () {
  10462. this._depthMask = true;
  10463. this._depthTest = true;
  10464. this._depthFunc = null;
  10465. this._cullFace = null;
  10466. this._cull = null;
  10467. this._zOffset = 0;
  10468. this._frontFace = null;
  10469. this._isDepthTestDirty = true;
  10470. this._isDepthMaskDirty = true;
  10471. this._isDepthFuncDirty = false;
  10472. this._isCullFaceDirty = false;
  10473. this._isCullDirty = false;
  10474. this._isZOffsetDirty = false;
  10475. this._isFrontFaceDirty = false;
  10476. };
  10477. _DepthCullingState.prototype.apply = function (gl) {
  10478. if (!this.isDirty) {
  10479. return;
  10480. }
  10481. // Cull
  10482. if (this._isCullDirty) {
  10483. if (this.cull) {
  10484. gl.enable(gl.CULL_FACE);
  10485. }
  10486. else {
  10487. gl.disable(gl.CULL_FACE);
  10488. }
  10489. this._isCullDirty = false;
  10490. }
  10491. // Cull face
  10492. if (this._isCullFaceDirty) {
  10493. gl.cullFace(this.cullFace);
  10494. this._isCullFaceDirty = false;
  10495. }
  10496. // Depth mask
  10497. if (this._isDepthMaskDirty) {
  10498. gl.depthMask(this.depthMask);
  10499. this._isDepthMaskDirty = false;
  10500. }
  10501. // Depth test
  10502. if (this._isDepthTestDirty) {
  10503. if (this.depthTest) {
  10504. gl.enable(gl.DEPTH_TEST);
  10505. }
  10506. else {
  10507. gl.disable(gl.DEPTH_TEST);
  10508. }
  10509. this._isDepthTestDirty = false;
  10510. }
  10511. // Depth func
  10512. if (this._isDepthFuncDirty) {
  10513. gl.depthFunc(this.depthFunc);
  10514. this._isDepthFuncDirty = false;
  10515. }
  10516. // zOffset
  10517. if (this._isZOffsetDirty) {
  10518. if (this.zOffset) {
  10519. gl.enable(gl.POLYGON_OFFSET_FILL);
  10520. gl.polygonOffset(this.zOffset, 0);
  10521. }
  10522. else {
  10523. gl.disable(gl.POLYGON_OFFSET_FILL);
  10524. }
  10525. this._isZOffsetDirty = false;
  10526. }
  10527. // Front face
  10528. if (this._isFrontFaceDirty) {
  10529. gl.frontFace(this.frontFace);
  10530. this._isFrontFaceDirty = false;
  10531. }
  10532. };
  10533. return _DepthCullingState;
  10534. }());
  10535. BABYLON._DepthCullingState = _DepthCullingState;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.depthCullingState.js.map
  10538. var BABYLON;
  10539. (function (BABYLON) {
  10540. var _StencilState = /** @class */ (function () {
  10541. function _StencilState() {
  10542. this._isStencilTestDirty = false;
  10543. this._isStencilMaskDirty = false;
  10544. this._isStencilFuncDirty = false;
  10545. this._isStencilOpDirty = false;
  10546. this.reset();
  10547. }
  10548. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10549. get: function () {
  10550. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10556. get: function () {
  10557. return this._stencilFunc;
  10558. },
  10559. set: function (value) {
  10560. if (this._stencilFunc === value) {
  10561. return;
  10562. }
  10563. this._stencilFunc = value;
  10564. this._isStencilFuncDirty = true;
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10570. get: function () {
  10571. return this._stencilFuncRef;
  10572. },
  10573. set: function (value) {
  10574. if (this._stencilFuncRef === value) {
  10575. return;
  10576. }
  10577. this._stencilFuncRef = value;
  10578. this._isStencilFuncDirty = true;
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10584. get: function () {
  10585. return this._stencilFuncMask;
  10586. },
  10587. set: function (value) {
  10588. if (this._stencilFuncMask === value) {
  10589. return;
  10590. }
  10591. this._stencilFuncMask = value;
  10592. this._isStencilFuncDirty = true;
  10593. },
  10594. enumerable: true,
  10595. configurable: true
  10596. });
  10597. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10598. get: function () {
  10599. return this._stencilOpStencilFail;
  10600. },
  10601. set: function (value) {
  10602. if (this._stencilOpStencilFail === value) {
  10603. return;
  10604. }
  10605. this._stencilOpStencilFail = value;
  10606. this._isStencilOpDirty = true;
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10612. get: function () {
  10613. return this._stencilOpDepthFail;
  10614. },
  10615. set: function (value) {
  10616. if (this._stencilOpDepthFail === value) {
  10617. return;
  10618. }
  10619. this._stencilOpDepthFail = value;
  10620. this._isStencilOpDirty = true;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10626. get: function () {
  10627. return this._stencilOpStencilDepthPass;
  10628. },
  10629. set: function (value) {
  10630. if (this._stencilOpStencilDepthPass === value) {
  10631. return;
  10632. }
  10633. this._stencilOpStencilDepthPass = value;
  10634. this._isStencilOpDirty = true;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10640. get: function () {
  10641. return this._stencilMask;
  10642. },
  10643. set: function (value) {
  10644. if (this._stencilMask === value) {
  10645. return;
  10646. }
  10647. this._stencilMask = value;
  10648. this._isStencilMaskDirty = true;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10654. get: function () {
  10655. return this._stencilTest;
  10656. },
  10657. set: function (value) {
  10658. if (this._stencilTest === value) {
  10659. return;
  10660. }
  10661. this._stencilTest = value;
  10662. this._isStencilTestDirty = true;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. _StencilState.prototype.reset = function () {
  10668. this._stencilTest = false;
  10669. this._stencilMask = 0xFF;
  10670. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10671. this._stencilFuncRef = 1;
  10672. this._stencilFuncMask = 0xFF;
  10673. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10674. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10675. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10676. this._isStencilTestDirty = true;
  10677. this._isStencilMaskDirty = true;
  10678. this._isStencilFuncDirty = true;
  10679. this._isStencilOpDirty = true;
  10680. };
  10681. _StencilState.prototype.apply = function (gl) {
  10682. if (!this.isDirty) {
  10683. return;
  10684. }
  10685. // Stencil test
  10686. if (this._isStencilTestDirty) {
  10687. if (this.stencilTest) {
  10688. gl.enable(gl.STENCIL_TEST);
  10689. }
  10690. else {
  10691. gl.disable(gl.STENCIL_TEST);
  10692. }
  10693. this._isStencilTestDirty = false;
  10694. }
  10695. // Stencil mask
  10696. if (this._isStencilMaskDirty) {
  10697. gl.stencilMask(this.stencilMask);
  10698. this._isStencilMaskDirty = false;
  10699. }
  10700. // Stencil func
  10701. if (this._isStencilFuncDirty) {
  10702. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10703. this._isStencilFuncDirty = false;
  10704. }
  10705. // Stencil op
  10706. if (this._isStencilOpDirty) {
  10707. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10708. this._isStencilOpDirty = false;
  10709. }
  10710. };
  10711. return _StencilState;
  10712. }());
  10713. BABYLON._StencilState = _StencilState;
  10714. })(BABYLON || (BABYLON = {}));
  10715. //# sourceMappingURL=babylon.stencilState.js.map
  10716. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10717. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10718. s = arguments[i];
  10719. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10720. t[p] = s[p];
  10721. }
  10722. return t;
  10723. };
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10727. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10728. };
  10729. var compileRawShader = function (gl, source, type) {
  10730. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10731. gl.shaderSource(shader, source);
  10732. gl.compileShader(shader);
  10733. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10734. var log = gl.getShaderInfoLog(shader);
  10735. if (log) {
  10736. throw new Error(log);
  10737. }
  10738. }
  10739. if (!shader) {
  10740. throw new Error("Something went wrong while compile the shader.");
  10741. }
  10742. return shader;
  10743. };
  10744. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10745. var magFilter = gl.NEAREST;
  10746. var minFilter = gl.NEAREST;
  10747. switch (samplingMode) {
  10748. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10749. magFilter = gl.LINEAR;
  10750. if (generateMipMaps) {
  10751. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10752. }
  10753. else {
  10754. minFilter = gl.LINEAR;
  10755. }
  10756. break;
  10757. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10758. magFilter = gl.LINEAR;
  10759. if (generateMipMaps) {
  10760. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10761. }
  10762. else {
  10763. minFilter = gl.LINEAR;
  10764. }
  10765. break;
  10766. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10767. magFilter = gl.NEAREST;
  10768. if (generateMipMaps) {
  10769. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10770. }
  10771. else {
  10772. minFilter = gl.NEAREST;
  10773. }
  10774. break;
  10775. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10776. magFilter = gl.NEAREST;
  10777. if (generateMipMaps) {
  10778. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10779. }
  10780. else {
  10781. minFilter = gl.NEAREST;
  10782. }
  10783. break;
  10784. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10785. magFilter = gl.NEAREST;
  10786. if (generateMipMaps) {
  10787. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10788. }
  10789. else {
  10790. minFilter = gl.LINEAR;
  10791. }
  10792. break;
  10793. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10794. magFilter = gl.NEAREST;
  10795. if (generateMipMaps) {
  10796. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10797. }
  10798. else {
  10799. minFilter = gl.LINEAR;
  10800. }
  10801. break;
  10802. case BABYLON.Texture.NEAREST_LINEAR:
  10803. magFilter = gl.NEAREST;
  10804. minFilter = gl.LINEAR;
  10805. break;
  10806. case BABYLON.Texture.NEAREST_NEAREST:
  10807. magFilter = gl.NEAREST;
  10808. minFilter = gl.NEAREST;
  10809. break;
  10810. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10811. magFilter = gl.LINEAR;
  10812. if (generateMipMaps) {
  10813. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10814. }
  10815. else {
  10816. minFilter = gl.NEAREST;
  10817. }
  10818. break;
  10819. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10820. magFilter = gl.LINEAR;
  10821. if (generateMipMaps) {
  10822. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10823. }
  10824. else {
  10825. minFilter = gl.NEAREST;
  10826. }
  10827. break;
  10828. case BABYLON.Texture.LINEAR_LINEAR:
  10829. magFilter = gl.LINEAR;
  10830. minFilter = gl.LINEAR;
  10831. break;
  10832. case BABYLON.Texture.LINEAR_NEAREST:
  10833. magFilter = gl.LINEAR;
  10834. minFilter = gl.NEAREST;
  10835. break;
  10836. }
  10837. return {
  10838. min: minFilter,
  10839. mag: magFilter
  10840. };
  10841. };
  10842. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10843. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10844. var img;
  10845. var onload = function () {
  10846. loadedImages[index] = img;
  10847. loadedImages._internalCount++;
  10848. if (scene) {
  10849. scene._removePendingData(img);
  10850. }
  10851. if (loadedImages._internalCount === 6) {
  10852. onfinish(loadedImages);
  10853. }
  10854. };
  10855. var onerror = function (message, exception) {
  10856. if (scene) {
  10857. scene._removePendingData(img);
  10858. }
  10859. if (onErrorCallBack) {
  10860. onErrorCallBack(message, exception);
  10861. }
  10862. };
  10863. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10864. if (scene) {
  10865. scene._addPendingData(img);
  10866. }
  10867. };
  10868. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10869. if (onError === void 0) { onError = null; }
  10870. var loadedImages = [];
  10871. loadedImages._internalCount = 0;
  10872. for (var index = 0; index < 6; index++) {
  10873. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10874. }
  10875. };
  10876. var BufferPointer = /** @class */ (function () {
  10877. function BufferPointer() {
  10878. }
  10879. return BufferPointer;
  10880. }());
  10881. /**
  10882. * Interface for attribute information associated with buffer instanciation
  10883. */
  10884. var InstancingAttributeInfo = /** @class */ (function () {
  10885. function InstancingAttributeInfo() {
  10886. }
  10887. return InstancingAttributeInfo;
  10888. }());
  10889. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10890. /**
  10891. * Define options used to create a render target texture
  10892. */
  10893. var RenderTargetCreationOptions = /** @class */ (function () {
  10894. function RenderTargetCreationOptions() {
  10895. }
  10896. return RenderTargetCreationOptions;
  10897. }());
  10898. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10899. /**
  10900. * Define options used to create a depth texture
  10901. */
  10902. var DepthTextureCreationOptions = /** @class */ (function () {
  10903. function DepthTextureCreationOptions() {
  10904. }
  10905. return DepthTextureCreationOptions;
  10906. }());
  10907. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10908. /**
  10909. * Class used to describe the capabilities of the engine relatively to the current browser
  10910. */
  10911. var EngineCapabilities = /** @class */ (function () {
  10912. function EngineCapabilities() {
  10913. }
  10914. return EngineCapabilities;
  10915. }());
  10916. BABYLON.EngineCapabilities = EngineCapabilities;
  10917. /**
  10918. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10919. */
  10920. var Engine = /** @class */ (function () {
  10921. /**
  10922. * Creates a new engine
  10923. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10924. * @param antialias defines enable antialiasing (default: false)
  10925. * @param options defines further options to be sent to the getContext() function
  10926. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10927. */
  10928. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10929. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10930. var _this = this;
  10931. // Public members
  10932. /**
  10933. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10934. */
  10935. this.forcePOTTextures = false;
  10936. /**
  10937. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10938. */
  10939. this.isFullscreen = false;
  10940. /**
  10941. * Gets a boolean indicating if the pointer is currently locked
  10942. */
  10943. this.isPointerLock = false;
  10944. /**
  10945. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10946. */
  10947. this.cullBackFaces = true;
  10948. /**
  10949. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10950. */
  10951. this.renderEvenInBackground = true;
  10952. /**
  10953. * Gets or sets a boolean indicating that cache can be kept between frames
  10954. */
  10955. this.preventCacheWipeBetweenFrames = false;
  10956. /**
  10957. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10958. **/
  10959. this.enableOfflineSupport = false;
  10960. /**
  10961. * Gets the list of created scenes
  10962. */
  10963. this.scenes = new Array();
  10964. /**
  10965. * Gets the list of created postprocesses
  10966. */
  10967. this.postProcesses = new Array();
  10968. // Observables
  10969. /**
  10970. * Observable event triggered each time the rendering canvas is resized
  10971. */
  10972. this.onResizeObservable = new BABYLON.Observable();
  10973. /**
  10974. * Observable event triggered each time the canvas loses focus
  10975. */
  10976. this.onCanvasBlurObservable = new BABYLON.Observable();
  10977. /**
  10978. * Observable event triggered each time the canvas gains focus
  10979. */
  10980. this.onCanvasFocusObservable = new BABYLON.Observable();
  10981. /**
  10982. * Observable event triggered each time the canvas receives pointerout event
  10983. */
  10984. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10985. /**
  10986. * Observable event triggered before each texture is initialized
  10987. */
  10988. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10989. //WebVR
  10990. this._vrDisplay = undefined;
  10991. this._vrSupported = false;
  10992. this._vrExclusivePointerMode = false;
  10993. // Uniform buffers list
  10994. /**
  10995. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10996. */
  10997. this.disableUniformBuffers = false;
  10998. /** @ignore */
  10999. this._uniformBuffers = new Array();
  11000. // Observables
  11001. /**
  11002. * Observable raised when the engine begins a new frame
  11003. */
  11004. this.onBeginFrameObservable = new BABYLON.Observable();
  11005. /**
  11006. * Observable raised when the engine ends the current frame
  11007. */
  11008. this.onEndFrameObservable = new BABYLON.Observable();
  11009. /**
  11010. * Observable raised when the engine is about to compile a shader
  11011. */
  11012. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11013. /**
  11014. * Observable raised when the engine has jsut compiled a shader
  11015. */
  11016. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11017. this._windowIsBackground = false;
  11018. this._webGLVersion = 1.0;
  11019. /** @ignore */
  11020. this._badOS = false;
  11021. /** @ignore */
  11022. this._badDesktopOS = false;
  11023. /**
  11024. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11025. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11026. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11027. */
  11028. this.disableTextureBindingOptimization = false;
  11029. /**
  11030. * Observable signaled when VR display mode changes
  11031. */
  11032. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11033. /**
  11034. * Observable signaled when VR request present is complete
  11035. */
  11036. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11037. /**
  11038. * Observable signaled when VR request present starts
  11039. */
  11040. this.onVRRequestPresentStart = new BABYLON.Observable();
  11041. this._colorWrite = true;
  11042. /** @ignore */
  11043. this._drawCalls = new BABYLON.PerfCounter();
  11044. /** @ignore */
  11045. this._textureCollisions = new BABYLON.PerfCounter();
  11046. this._renderingQueueLaunched = false;
  11047. this._activeRenderLoops = new Array();
  11048. // Deterministic lockstepMaxSteps
  11049. this._deterministicLockstep = false;
  11050. this._lockstepMaxSteps = 4;
  11051. // Lost context
  11052. /**
  11053. * Observable signaled when a context lost event is raised
  11054. */
  11055. this.onContextLostObservable = new BABYLON.Observable();
  11056. /**
  11057. * Observable signaled when a context restored event is raised
  11058. */
  11059. this.onContextRestoredObservable = new BABYLON.Observable();
  11060. this._contextWasLost = false;
  11061. this._doNotHandleContextLost = false;
  11062. // FPS
  11063. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11064. this._fps = 60;
  11065. this._deltaTime = 0;
  11066. /**
  11067. * Turn this value on if you want to pause FPS computation when in background
  11068. */
  11069. this.disablePerformanceMonitorInBackground = false;
  11070. // States
  11071. /** @ignore */
  11072. this._depthCullingState = new BABYLON._DepthCullingState();
  11073. /** @ignore */
  11074. this._stencilState = new BABYLON._StencilState();
  11075. /** @ignore */
  11076. this._alphaState = new BABYLON._AlphaState();
  11077. /** @ignore */
  11078. this._alphaMode = Engine.ALPHA_DISABLE;
  11079. // Cache
  11080. this._internalTexturesCache = new Array();
  11081. /** @ignore */
  11082. this._activeChannel = 0;
  11083. this._currentTextureChannel = -1;
  11084. /** @ignore */
  11085. this._boundTexturesCache = {};
  11086. this._compiledEffects = {};
  11087. this._vertexAttribArraysEnabled = [];
  11088. this._uintIndicesCurrentlySet = false;
  11089. this._currentBoundBuffer = new Array();
  11090. this._currentBufferPointers = new Array();
  11091. this._currentInstanceLocations = new Array();
  11092. this._currentInstanceBuffers = new Array();
  11093. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11094. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11095. this._vaoRecordInProgress = false;
  11096. this._mustWipeVertexAttributes = false;
  11097. this._nextFreeTextureSlots = new Array();
  11098. this._maxSimultaneousTextures = 0;
  11099. this._activeRequests = new Array();
  11100. // Hardware supported Compressed Textures
  11101. this._texturesSupported = new Array();
  11102. this._onVRFullScreenTriggered = function () {
  11103. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11104. //get the old size before we change
  11105. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11106. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11107. //get the width and height, change the render size
  11108. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11109. _this.setHardwareScalingLevel(1);
  11110. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11111. }
  11112. else {
  11113. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11114. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11115. }
  11116. };
  11117. this._boundUniforms = {};
  11118. // Register promises
  11119. BABYLON.PromisePolyfill.Apply();
  11120. var canvas = null;
  11121. Engine.Instances.push(this);
  11122. if (!canvasOrContext) {
  11123. return;
  11124. }
  11125. options = options || {};
  11126. if (canvasOrContext.getContext) {
  11127. canvas = canvasOrContext;
  11128. this._renderingCanvas = canvas;
  11129. if (antialias != null) {
  11130. options.antialias = antialias;
  11131. }
  11132. if (options.deterministicLockstep === undefined) {
  11133. options.deterministicLockstep = false;
  11134. }
  11135. if (options.lockstepMaxSteps === undefined) {
  11136. options.lockstepMaxSteps = 4;
  11137. }
  11138. if (options.preserveDrawingBuffer === undefined) {
  11139. options.preserveDrawingBuffer = false;
  11140. }
  11141. if (options.audioEngine === undefined) {
  11142. options.audioEngine = true;
  11143. }
  11144. if (options.stencil === undefined) {
  11145. options.stencil = true;
  11146. }
  11147. this._deterministicLockstep = options.deterministicLockstep;
  11148. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11149. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11150. // Exceptions
  11151. if (navigator && navigator.userAgent) {
  11152. var ua = navigator.userAgent;
  11153. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11154. var exception = _a[_i];
  11155. var key = exception.key;
  11156. var targets = exception.targets;
  11157. if (ua.indexOf(key) > -1) {
  11158. if (exception.capture && exception.captureConstraint) {
  11159. var capture = exception.capture;
  11160. var constraint = exception.captureConstraint;
  11161. var regex = new RegExp(capture);
  11162. var matches = regex.exec(ua);
  11163. if (matches && matches.length > 0) {
  11164. var capturedValue = parseInt(matches[matches.length - 1]);
  11165. if (capturedValue >= constraint) {
  11166. continue;
  11167. }
  11168. }
  11169. }
  11170. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11171. var target = targets_1[_b];
  11172. switch (target) {
  11173. case "uniformBuffer":
  11174. this.disableUniformBuffers = true;
  11175. break;
  11176. case "textureBindingOptimization":
  11177. this.disableTextureBindingOptimization = true;
  11178. break;
  11179. }
  11180. }
  11181. }
  11182. }
  11183. }
  11184. // GL
  11185. if (!options.disableWebGL2Support) {
  11186. try {
  11187. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11188. if (this._gl) {
  11189. this._webGLVersion = 2.0;
  11190. }
  11191. }
  11192. catch (e) {
  11193. // Do nothing
  11194. }
  11195. }
  11196. if (!this._gl) {
  11197. if (!canvas) {
  11198. throw new Error("The provided canvas is null or undefined.");
  11199. }
  11200. try {
  11201. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11202. }
  11203. catch (e) {
  11204. throw new Error("WebGL not supported");
  11205. }
  11206. }
  11207. if (!this._gl) {
  11208. throw new Error("WebGL not supported");
  11209. }
  11210. this._onCanvasFocus = function () {
  11211. _this.onCanvasFocusObservable.notifyObservers(_this);
  11212. };
  11213. this._onCanvasBlur = function () {
  11214. _this.onCanvasBlurObservable.notifyObservers(_this);
  11215. };
  11216. canvas.addEventListener("focus", this._onCanvasFocus);
  11217. canvas.addEventListener("blur", this._onCanvasBlur);
  11218. this._onBlur = function () {
  11219. if (_this.disablePerformanceMonitorInBackground) {
  11220. _this._performanceMonitor.disable();
  11221. }
  11222. _this._windowIsBackground = true;
  11223. };
  11224. this._onFocus = function () {
  11225. if (_this.disablePerformanceMonitorInBackground) {
  11226. _this._performanceMonitor.enable();
  11227. }
  11228. _this._windowIsBackground = false;
  11229. };
  11230. this._onCanvasPointerOut = function (ev) {
  11231. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11232. };
  11233. window.addEventListener("blur", this._onBlur);
  11234. window.addEventListener("focus", this._onFocus);
  11235. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11236. // Context lost
  11237. if (!this._doNotHandleContextLost) {
  11238. this._onContextLost = function (evt) {
  11239. evt.preventDefault();
  11240. _this._contextWasLost = true;
  11241. BABYLON.Tools.Warn("WebGL context lost.");
  11242. _this.onContextLostObservable.notifyObservers(_this);
  11243. };
  11244. this._onContextRestored = function (evt) {
  11245. // Adding a timeout to avoid race condition at browser level
  11246. setTimeout(function () {
  11247. // Rebuild gl context
  11248. _this._initGLContext();
  11249. // Rebuild effects
  11250. _this._rebuildEffects();
  11251. // Rebuild textures
  11252. _this._rebuildInternalTextures();
  11253. // Rebuild buffers
  11254. _this._rebuildBuffers();
  11255. // Cache
  11256. _this.wipeCaches(true);
  11257. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11258. _this.onContextRestoredObservable.notifyObservers(_this);
  11259. _this._contextWasLost = false;
  11260. }, 0);
  11261. };
  11262. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11263. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11264. }
  11265. }
  11266. else {
  11267. this._gl = canvasOrContext;
  11268. this._renderingCanvas = this._gl.canvas;
  11269. if (this._gl.renderbufferStorageMultisample) {
  11270. this._webGLVersion = 2.0;
  11271. }
  11272. options.stencil = this._gl.getContextAttributes().stencil;
  11273. }
  11274. // Viewport
  11275. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11276. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11277. this.resize();
  11278. this._isStencilEnable = options.stencil ? true : false;
  11279. this._initGLContext();
  11280. if (canvas) {
  11281. // Fullscreen
  11282. this._onFullscreenChange = function () {
  11283. if (document.fullscreen !== undefined) {
  11284. _this.isFullscreen = document.fullscreen;
  11285. }
  11286. else if (document.mozFullScreen !== undefined) {
  11287. _this.isFullscreen = document.mozFullScreen;
  11288. }
  11289. else if (document.webkitIsFullScreen !== undefined) {
  11290. _this.isFullscreen = document.webkitIsFullScreen;
  11291. }
  11292. else if (document.msIsFullScreen !== undefined) {
  11293. _this.isFullscreen = document.msIsFullScreen;
  11294. }
  11295. // Pointer lock
  11296. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11297. canvas.requestPointerLock = canvas.requestPointerLock ||
  11298. canvas.msRequestPointerLock ||
  11299. canvas.mozRequestPointerLock ||
  11300. canvas.webkitRequestPointerLock;
  11301. if (canvas.requestPointerLock) {
  11302. canvas.requestPointerLock();
  11303. }
  11304. }
  11305. };
  11306. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11307. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11308. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11309. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11310. // Pointer lock
  11311. this._onPointerLockChange = function () {
  11312. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11313. document.webkitPointerLockElement === canvas ||
  11314. document.msPointerLockElement === canvas ||
  11315. document.pointerLockElement === canvas);
  11316. };
  11317. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11318. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11319. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11320. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11321. this._onVRDisplayPointerRestricted = function () {
  11322. if (canvas) {
  11323. canvas.requestPointerLock();
  11324. }
  11325. };
  11326. this._onVRDisplayPointerUnrestricted = function () {
  11327. document.exitPointerLock();
  11328. };
  11329. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11330. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11331. }
  11332. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11333. Engine.audioEngine = new BABYLON.AudioEngine();
  11334. }
  11335. // Prepare buffer pointers
  11336. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11337. this._currentBufferPointers[i] = new BufferPointer();
  11338. }
  11339. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11340. // Load WebVR Devices
  11341. if (options.autoEnableWebVR) {
  11342. this.initWebVR();
  11343. }
  11344. // Detect if we are running on a faulty buggy OS.
  11345. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11346. // Detect if we are running on a faulty buggy desktop OS.
  11347. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11348. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11349. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11350. }
  11351. Object.defineProperty(Engine, "LastCreatedEngine", {
  11352. /**
  11353. * Gets the latest created engine
  11354. */
  11355. get: function () {
  11356. if (Engine.Instances.length === 0) {
  11357. return null;
  11358. }
  11359. return Engine.Instances[Engine.Instances.length - 1];
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(Engine, "LastCreatedScene", {
  11365. /**
  11366. * Gets the latest created scene
  11367. */
  11368. get: function () {
  11369. var lastCreatedEngine = Engine.LastCreatedEngine;
  11370. if (!lastCreatedEngine) {
  11371. return null;
  11372. }
  11373. if (lastCreatedEngine.scenes.length === 0) {
  11374. return null;
  11375. }
  11376. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. /**
  11382. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11383. * @param flag defines which part of the materials must be marked as dirty
  11384. * @param predicate defines a predicate used to filter which materials should be affected
  11385. */
  11386. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11387. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11388. var engine = Engine.Instances[engineIndex];
  11389. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11390. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11391. }
  11392. }
  11393. };
  11394. Object.defineProperty(Engine, "NEVER", {
  11395. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11396. get: function () {
  11397. return Engine._NEVER;
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. Object.defineProperty(Engine, "ALWAYS", {
  11403. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11404. get: function () {
  11405. return Engine._ALWAYS;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(Engine, "LESS", {
  11411. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11412. get: function () {
  11413. return Engine._LESS;
  11414. },
  11415. enumerable: true,
  11416. configurable: true
  11417. });
  11418. Object.defineProperty(Engine, "EQUAL", {
  11419. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11420. get: function () {
  11421. return Engine._EQUAL;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(Engine, "LEQUAL", {
  11427. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11428. get: function () {
  11429. return Engine._LEQUAL;
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(Engine, "GREATER", {
  11435. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11436. get: function () {
  11437. return Engine._GREATER;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(Engine, "GEQUAL", {
  11443. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11444. get: function () {
  11445. return Engine._GEQUAL;
  11446. },
  11447. enumerable: true,
  11448. configurable: true
  11449. });
  11450. Object.defineProperty(Engine, "NOTEQUAL", {
  11451. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11452. get: function () {
  11453. return Engine._NOTEQUAL;
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Engine, "KEEP", {
  11459. /** Passed to stencilOperation to specify that stencil value must be kept */
  11460. get: function () {
  11461. return Engine._KEEP;
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. Object.defineProperty(Engine, "REPLACE", {
  11467. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11468. get: function () {
  11469. return Engine._REPLACE;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Object.defineProperty(Engine, "INCR", {
  11475. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11476. get: function () {
  11477. return Engine._INCR;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(Engine, "DECR", {
  11483. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11484. get: function () {
  11485. return Engine._DECR;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(Engine, "INVERT", {
  11491. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11492. get: function () {
  11493. return Engine._INVERT;
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. Object.defineProperty(Engine, "INCR_WRAP", {
  11499. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11500. get: function () {
  11501. return Engine._INCR_WRAP;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Engine, "DECR_WRAP", {
  11507. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11508. get: function () {
  11509. return Engine._DECR_WRAP;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11515. // Alpha
  11516. /** Defines that alpha blending is disabled */
  11517. get: function () {
  11518. return Engine._ALPHA_DISABLE;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11524. /** Defines that alpha blending to SRC + DEST */
  11525. get: function () {
  11526. return Engine._ALPHA_ONEONE;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Object.defineProperty(Engine, "ALPHA_ADD", {
  11532. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11533. get: function () {
  11534. return Engine._ALPHA_ADD;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11540. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11541. get: function () {
  11542. return Engine._ALPHA_COMBINE;
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11548. /** Defines that alpha blending to DEST - SRC * DEST */
  11549. get: function () {
  11550. return Engine._ALPHA_SUBTRACT;
  11551. },
  11552. enumerable: true,
  11553. configurable: true
  11554. });
  11555. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11556. /** Defines that alpha blending to SRC * DEST */
  11557. get: function () {
  11558. return Engine._ALPHA_MULTIPLY;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11564. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11565. get: function () {
  11566. return Engine._ALPHA_MAXIMIZED;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11572. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11573. get: function () {
  11574. return Engine._ALPHA_PREMULTIPLIED;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11580. /**
  11581. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11582. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11583. */
  11584. get: function () {
  11585. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11591. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11592. get: function () {
  11593. return Engine._ALPHA_INTERPOLATE;
  11594. },
  11595. enumerable: true,
  11596. configurable: true
  11597. });
  11598. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11599. /**
  11600. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11601. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11602. */
  11603. get: function () {
  11604. return Engine._ALPHA_SCREENMODE;
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11610. // Delays
  11611. /** Defines that the ressource is not delayed*/
  11612. get: function () {
  11613. return Engine._DELAYLOADSTATE_NONE;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11619. /** Defines that the ressource was successfully delay loaded */
  11620. get: function () {
  11621. return Engine._DELAYLOADSTATE_LOADED;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11627. /** Defines that the ressource is currently delay loading */
  11628. get: function () {
  11629. return Engine._DELAYLOADSTATE_LOADING;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11635. /** Defines that the ressource is delayed and has not started loading */
  11636. get: function () {
  11637. return Engine._DELAYLOADSTATE_NOTLOADED;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11643. /** ALPHA */
  11644. get: function () {
  11645. return Engine._TEXTUREFORMAT_ALPHA;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11651. /** LUMINANCE */
  11652. get: function () {
  11653. return Engine._TEXTUREFORMAT_LUMINANCE;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11659. /**
  11660. * R32F
  11661. */
  11662. get: function () {
  11663. return Engine._TEXTUREFORMAT_R32F;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11669. /**
  11670. * RG32F
  11671. */
  11672. get: function () {
  11673. return Engine._TEXTUREFORMAT_RG32F;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11679. /**
  11680. * RGB32F
  11681. */
  11682. get: function () {
  11683. return Engine._TEXTUREFORMAT_RGB32F;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11689. /**
  11690. * RGBA32F
  11691. */
  11692. get: function () {
  11693. return Engine._TEXTUREFORMAT_RGBA32F;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11699. /** LUMINANCE_ALPHA */
  11700. get: function () {
  11701. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11707. /** RGB */
  11708. get: function () {
  11709. return Engine._TEXTUREFORMAT_RGB;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11715. /** RGBA */
  11716. get: function () {
  11717. return Engine._TEXTUREFORMAT_RGBA;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11723. /** UNSIGNED_INT */
  11724. get: function () {
  11725. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11731. /** FLOAT */
  11732. get: function () {
  11733. return Engine._TEXTURETYPE_FLOAT;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11739. /** HALF_FLOAT */
  11740. get: function () {
  11741. return Engine._TEXTURETYPE_HALF_FLOAT;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11747. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11748. get: function () {
  11749. return Engine._SCALEMODE_FLOOR;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11755. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11756. get: function () {
  11757. return Engine._SCALEMODE_NEAREST;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11763. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11764. get: function () {
  11765. return Engine._SCALEMODE_CEILING;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine, "Version", {
  11771. /**
  11772. * Returns the current version of the framework
  11773. */
  11774. get: function () {
  11775. return "3.2.0-beta.5";
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11781. /**
  11782. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11783. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11784. */
  11785. get: function () {
  11786. return this._vrExclusivePointerMode;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11792. /**
  11793. * Gets a boolean indicating that the engine supports uniform buffers
  11794. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11795. */
  11796. get: function () {
  11797. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11803. /**
  11804. * Gets a boolean indicating that only power of 2 textures are supported
  11805. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11806. */
  11807. get: function () {
  11808. return this._webGLVersion < 2 || this.forcePOTTextures;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11814. /**
  11815. * Gets the performance monitor attached to this engine
  11816. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11817. */
  11818. get: function () {
  11819. return this._performanceMonitor;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11825. /**
  11826. * Gets the list of texture formats supported
  11827. */
  11828. get: function () {
  11829. return this._texturesSupported;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11835. /**
  11836. * Gets the list of texture formats in use
  11837. */
  11838. get: function () {
  11839. return this._textureFormatInUse;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "currentViewport", {
  11845. /**
  11846. * Gets the current viewport
  11847. */
  11848. get: function () {
  11849. return this._cachedViewport;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11855. /**
  11856. * Gets the default empty texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture) {
  11860. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11868. /**
  11869. * Gets the default empty 3D texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyTexture3D) {
  11873. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11874. }
  11875. return this._emptyTexture3D;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11881. /**
  11882. * Gets the default empty cube texture
  11883. */
  11884. get: function () {
  11885. if (!this._emptyCubeTexture) {
  11886. var faceData = new Uint8Array(4);
  11887. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11888. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11889. }
  11890. return this._emptyCubeTexture;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Engine.prototype._rebuildInternalTextures = function () {
  11896. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11897. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11898. var internalTexture = currentState_1[_i];
  11899. internalTexture._rebuild();
  11900. }
  11901. };
  11902. Engine.prototype._rebuildEffects = function () {
  11903. for (var key in this._compiledEffects) {
  11904. var effect = this._compiledEffects[key];
  11905. effect._prepareEffect();
  11906. }
  11907. BABYLON.Effect.ResetCache();
  11908. };
  11909. Engine.prototype._rebuildBuffers = function () {
  11910. // Index / Vertex
  11911. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11912. var scene = _a[_i];
  11913. scene.resetCachedMaterial();
  11914. scene._rebuildGeometries();
  11915. scene._rebuildTextures();
  11916. }
  11917. // Uniforms
  11918. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11919. var uniformBuffer = _c[_b];
  11920. uniformBuffer._rebuild();
  11921. }
  11922. };
  11923. Engine.prototype._initGLContext = function () {
  11924. // Caps
  11925. this._caps = new EngineCapabilities();
  11926. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11927. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11928. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11929. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11930. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11931. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11932. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11933. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11934. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11935. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11936. // Infos
  11937. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11938. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11939. if (rendererInfo != null) {
  11940. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11941. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11942. }
  11943. if (!this._glVendor) {
  11944. this._glVendor = "Unknown vendor";
  11945. }
  11946. if (!this._glRenderer) {
  11947. this._glRenderer = "Unknown renderer";
  11948. }
  11949. // Constants
  11950. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11951. if (this._gl.RGBA16F !== 0x881A) {
  11952. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11953. }
  11954. if (this._gl.RGBA32F !== 0x8814) {
  11955. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11956. }
  11957. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11958. this._gl.DEPTH24_STENCIL8 = 35056;
  11959. }
  11960. // Extensions
  11961. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11962. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11963. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11964. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11965. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11966. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11967. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11968. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11969. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11970. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11971. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11972. this._caps.highPrecisionShaderSupported = true;
  11973. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11974. if (this._caps.timerQuery) {
  11975. if (this._webGLVersion === 1) {
  11976. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11977. }
  11978. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11979. }
  11980. // Checks if some of the format renders first to allow the use of webgl inspector.
  11981. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11982. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11983. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11984. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11985. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11986. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11987. if (this._webGLVersion > 1) {
  11988. this._gl.HALF_FLOAT_OES = 0x140B;
  11989. }
  11990. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11991. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11992. // Draw buffers
  11993. if (this._webGLVersion > 1) {
  11994. this._caps.drawBuffersExtension = true;
  11995. }
  11996. else {
  11997. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11998. if (drawBuffersExtension !== null) {
  11999. this._caps.drawBuffersExtension = true;
  12000. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12001. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12002. for (var i = 0; i < 16; i++) {
  12003. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12004. }
  12005. }
  12006. else {
  12007. this._caps.drawBuffersExtension = false;
  12008. }
  12009. }
  12010. // Depth Texture
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.depthTextureExtension = true;
  12013. }
  12014. else {
  12015. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12016. if (depthTextureExtension != null) {
  12017. this._caps.depthTextureExtension = true;
  12018. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12019. }
  12020. }
  12021. // Vertex array object
  12022. if (this._webGLVersion > 1) {
  12023. this._caps.vertexArrayObject = true;
  12024. }
  12025. else {
  12026. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12027. if (vertexArrayObjectExtension != null) {
  12028. this._caps.vertexArrayObject = true;
  12029. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12030. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12031. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12032. }
  12033. else {
  12034. this._caps.vertexArrayObject = false;
  12035. }
  12036. }
  12037. // Instances count
  12038. if (this._webGLVersion > 1) {
  12039. this._caps.instancedArrays = true;
  12040. }
  12041. else {
  12042. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12043. if (instanceExtension != null) {
  12044. this._caps.instancedArrays = true;
  12045. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12046. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12047. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12048. }
  12049. else {
  12050. this._caps.instancedArrays = false;
  12051. }
  12052. }
  12053. // Intelligently add supported compressed formats in order to check for.
  12054. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12055. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12056. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12057. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12058. if (this._caps.astc)
  12059. this.texturesSupported.push('-astc.ktx');
  12060. if (this._caps.s3tc)
  12061. this.texturesSupported.push('-dxt.ktx');
  12062. if (this._caps.pvrtc)
  12063. this.texturesSupported.push('-pvrtc.ktx');
  12064. if (this._caps.etc2)
  12065. this.texturesSupported.push('-etc2.ktx');
  12066. if (this._caps.etc1)
  12067. this.texturesSupported.push('-etc1.ktx');
  12068. if (this._gl.getShaderPrecisionFormat) {
  12069. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12070. if (highp) {
  12071. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12072. }
  12073. }
  12074. // Depth buffer
  12075. this.setDepthBuffer(true);
  12076. this.setDepthFunctionToLessOrEqual();
  12077. this.setDepthWrite(true);
  12078. // Texture maps
  12079. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12080. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12081. this._nextFreeTextureSlots.push(slot);
  12082. }
  12083. };
  12084. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12085. /**
  12086. * Gets version of the current webGL context
  12087. */
  12088. get: function () {
  12089. return this._webGLVersion;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12095. /**
  12096. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12097. */
  12098. get: function () {
  12099. return this._isStencilEnable;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Engine.prototype._prepareWorkingCanvas = function () {
  12105. if (this._workingCanvas) {
  12106. return;
  12107. }
  12108. this._workingCanvas = document.createElement("canvas");
  12109. var context = this._workingCanvas.getContext("2d");
  12110. if (context) {
  12111. this._workingContext = context;
  12112. }
  12113. };
  12114. /**
  12115. * Reset the texture cache to empty state
  12116. */
  12117. Engine.prototype.resetTextureCache = function () {
  12118. for (var key in this._boundTexturesCache) {
  12119. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12120. continue;
  12121. }
  12122. var boundTexture = this._boundTexturesCache[key];
  12123. if (boundTexture) {
  12124. this._removeDesignatedSlot(boundTexture);
  12125. }
  12126. this._boundTexturesCache[key] = null;
  12127. }
  12128. if (!this.disableTextureBindingOptimization) {
  12129. this._nextFreeTextureSlots = [];
  12130. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12131. this._nextFreeTextureSlots.push(slot);
  12132. }
  12133. }
  12134. this._currentTextureChannel = -1;
  12135. };
  12136. /**
  12137. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12138. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12139. * @returns true if engine is in deterministic lock step mode
  12140. */
  12141. Engine.prototype.isDeterministicLockStep = function () {
  12142. return this._deterministicLockstep;
  12143. };
  12144. /**
  12145. * Gets the max steps when engine is running in deterministic lock step
  12146. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12147. * @returns the max steps
  12148. */
  12149. Engine.prototype.getLockstepMaxSteps = function () {
  12150. return this._lockstepMaxSteps;
  12151. };
  12152. /**
  12153. * Gets an object containing information about the current webGL context
  12154. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12155. */
  12156. Engine.prototype.getGlInfo = function () {
  12157. return {
  12158. vendor: this._glVendor,
  12159. renderer: this._glRenderer,
  12160. version: this._glVersion
  12161. };
  12162. };
  12163. /**
  12164. * Gets current aspect ratio
  12165. * @param camera defines the camera to use to get the aspect ratio
  12166. * @param useScreen defines if screen size must be used (or the current render target if any)
  12167. * @returns a number defining the aspect ratio
  12168. */
  12169. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12170. if (useScreen === void 0) { useScreen = false; }
  12171. var viewport = camera.viewport;
  12172. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12173. };
  12174. /**
  12175. * Gets the current render width
  12176. * @param useScreen defines if screen size must be used (or the current render target if any)
  12177. * @returns a number defining the current render width
  12178. */
  12179. Engine.prototype.getRenderWidth = function (useScreen) {
  12180. if (useScreen === void 0) { useScreen = false; }
  12181. if (!useScreen && this._currentRenderTarget) {
  12182. return this._currentRenderTarget.width;
  12183. }
  12184. return this._gl.drawingBufferWidth;
  12185. };
  12186. /**
  12187. * Gets the current render height
  12188. * @param useScreen defines if screen size must be used (or the current render target if any)
  12189. * @returns a number defining the current render height
  12190. */
  12191. Engine.prototype.getRenderHeight = function (useScreen) {
  12192. if (useScreen === void 0) { useScreen = false; }
  12193. if (!useScreen && this._currentRenderTarget) {
  12194. return this._currentRenderTarget.height;
  12195. }
  12196. return this._gl.drawingBufferHeight;
  12197. };
  12198. /**
  12199. * Gets the HTML canvas attached with the current webGL context
  12200. * @returns a HTML canvas
  12201. */
  12202. Engine.prototype.getRenderingCanvas = function () {
  12203. return this._renderingCanvas;
  12204. };
  12205. /**
  12206. * Gets the client rect of the HTML canvas attached with the current webGL context
  12207. * @returns a client rectanglee
  12208. */
  12209. Engine.prototype.getRenderingCanvasClientRect = function () {
  12210. if (!this._renderingCanvas) {
  12211. return null;
  12212. }
  12213. return this._renderingCanvas.getBoundingClientRect();
  12214. };
  12215. /**
  12216. * Defines the hardware scaling level.
  12217. * By default the hardware scaling level is computed from the window device ratio.
  12218. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12219. * @param level defines the level to use
  12220. */
  12221. Engine.prototype.setHardwareScalingLevel = function (level) {
  12222. this._hardwareScalingLevel = level;
  12223. this.resize();
  12224. };
  12225. /**
  12226. * Gets the current hardware scaling level.
  12227. * By default the hardware scaling level is computed from the window device ratio.
  12228. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12229. * @returns a number indicating the current hardware scaling level
  12230. */
  12231. Engine.prototype.getHardwareScalingLevel = function () {
  12232. return this._hardwareScalingLevel;
  12233. };
  12234. /**
  12235. * Gets the list of loaded textures
  12236. * @returns an array containing all loaded textures
  12237. */
  12238. Engine.prototype.getLoadedTexturesCache = function () {
  12239. return this._internalTexturesCache;
  12240. };
  12241. /**
  12242. * Gets the object containing all engine capabilities
  12243. * @returns the EngineCapabilities object
  12244. */
  12245. Engine.prototype.getCaps = function () {
  12246. return this._caps;
  12247. };
  12248. Object.defineProperty(Engine.prototype, "drawCalls", {
  12249. /** @ignore */
  12250. get: function () {
  12251. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12252. return 0;
  12253. },
  12254. enumerable: true,
  12255. configurable: true
  12256. });
  12257. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12258. /** @ignore */
  12259. get: function () {
  12260. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12261. return null;
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. /**
  12267. * Gets the current depth function
  12268. * @returns a number defining the depth function
  12269. */
  12270. Engine.prototype.getDepthFunction = function () {
  12271. return this._depthCullingState.depthFunc;
  12272. };
  12273. /**
  12274. * Sets the current depth function
  12275. * @param depthFunc defines the function to use
  12276. */
  12277. Engine.prototype.setDepthFunction = function (depthFunc) {
  12278. this._depthCullingState.depthFunc = depthFunc;
  12279. };
  12280. /**
  12281. * Sets the current depth function to GREATER
  12282. */
  12283. Engine.prototype.setDepthFunctionToGreater = function () {
  12284. this._depthCullingState.depthFunc = this._gl.GREATER;
  12285. };
  12286. /**
  12287. * Sets the current depth function to GEQUAL
  12288. */
  12289. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12290. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12291. };
  12292. /**
  12293. * Sets the current depth function to LESS
  12294. */
  12295. Engine.prototype.setDepthFunctionToLess = function () {
  12296. this._depthCullingState.depthFunc = this._gl.LESS;
  12297. };
  12298. /**
  12299. * Sets the current depth function to LEQUAL
  12300. */
  12301. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12302. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12303. };
  12304. /**
  12305. * Gets a boolean indicating if stencil buffer is enabled
  12306. * @returns the current stencil buffer state
  12307. */
  12308. Engine.prototype.getStencilBuffer = function () {
  12309. return this._stencilState.stencilTest;
  12310. };
  12311. /**
  12312. * Enable or disable the stencil buffer
  12313. * @param enable defines if the stencil buffer must be enabled or disabled
  12314. */
  12315. Engine.prototype.setStencilBuffer = function (enable) {
  12316. this._stencilState.stencilTest = enable;
  12317. };
  12318. /**
  12319. * Gets the current stencil mask
  12320. * @returns a number defining the new stencil mask to use
  12321. */
  12322. Engine.prototype.getStencilMask = function () {
  12323. return this._stencilState.stencilMask;
  12324. };
  12325. /**
  12326. * Sets the current stencil mask
  12327. * @param mask defines the new stencil mask to use
  12328. */
  12329. Engine.prototype.setStencilMask = function (mask) {
  12330. this._stencilState.stencilMask = mask;
  12331. };
  12332. /**
  12333. * Gets the current stencil function
  12334. * @returns a number defining the stencil function to use
  12335. */
  12336. Engine.prototype.getStencilFunction = function () {
  12337. return this._stencilState.stencilFunc;
  12338. };
  12339. /**
  12340. * Gets the current stencil reference value
  12341. * @returns a number defining the stencil reference value to use
  12342. */
  12343. Engine.prototype.getStencilFunctionReference = function () {
  12344. return this._stencilState.stencilFuncRef;
  12345. };
  12346. /**
  12347. * Gets the current stencil mask
  12348. * @returns a number defining the stencil mask to use
  12349. */
  12350. Engine.prototype.getStencilFunctionMask = function () {
  12351. return this._stencilState.stencilFuncMask;
  12352. };
  12353. /**
  12354. * Sets the current stencil function
  12355. * @param stencilFunc defines the new stencil function to use
  12356. */
  12357. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12358. this._stencilState.stencilFunc = stencilFunc;
  12359. };
  12360. /**
  12361. * Sets the current stencil reference
  12362. * @param reference defines the new stencil reference to use
  12363. */
  12364. Engine.prototype.setStencilFunctionReference = function (reference) {
  12365. this._stencilState.stencilFuncRef = reference;
  12366. };
  12367. /**
  12368. * Sets the current stencil mask
  12369. * @param mask defines the new stencil mask to use
  12370. */
  12371. Engine.prototype.setStencilFunctionMask = function (mask) {
  12372. this._stencilState.stencilFuncMask = mask;
  12373. };
  12374. /**
  12375. * Gets the current stencil operation when stencil fails
  12376. * @returns a number defining stencil operation to use when stencil fails
  12377. */
  12378. Engine.prototype.getStencilOperationFail = function () {
  12379. return this._stencilState.stencilOpStencilFail;
  12380. };
  12381. /**
  12382. * Gets the current stencil operation when depth fails
  12383. * @returns a number defining stencil operation to use when depth fails
  12384. */
  12385. Engine.prototype.getStencilOperationDepthFail = function () {
  12386. return this._stencilState.stencilOpDepthFail;
  12387. };
  12388. /**
  12389. * Gets the current stencil operation when stencil passes
  12390. * @returns a number defining stencil operation to use when stencil passes
  12391. */
  12392. Engine.prototype.getStencilOperationPass = function () {
  12393. return this._stencilState.stencilOpStencilDepthPass;
  12394. };
  12395. /**
  12396. * Sets the stencil operation to use when stencil fails
  12397. * @param operation defines the stencil operation to use when stencil fails
  12398. */
  12399. Engine.prototype.setStencilOperationFail = function (operation) {
  12400. this._stencilState.stencilOpStencilFail = operation;
  12401. };
  12402. /**
  12403. * Sets the stencil operation to use when depth fails
  12404. * @param operation defines the stencil operation to use when depth fails
  12405. */
  12406. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12407. this._stencilState.stencilOpDepthFail = operation;
  12408. };
  12409. /**
  12410. * Sets the stencil operation to use when stencil passes
  12411. * @param operation defines the stencil operation to use when stencil passes
  12412. */
  12413. Engine.prototype.setStencilOperationPass = function (operation) {
  12414. this._stencilState.stencilOpStencilDepthPass = operation;
  12415. };
  12416. /**
  12417. * Sets a boolean indicating if the dithering state is enabled or disabled
  12418. * @param value defines the dithering state
  12419. */
  12420. Engine.prototype.setDitheringState = function (value) {
  12421. if (value) {
  12422. this._gl.enable(this._gl.DITHER);
  12423. }
  12424. else {
  12425. this._gl.disable(this._gl.DITHER);
  12426. }
  12427. };
  12428. /**
  12429. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12430. * @param value defines the rasterizer state
  12431. */
  12432. Engine.prototype.setRasterizerState = function (value) {
  12433. if (value) {
  12434. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12435. }
  12436. else {
  12437. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12438. }
  12439. };
  12440. /**
  12441. * stop executing a render loop function and remove it from the execution array
  12442. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12443. */
  12444. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12445. if (!renderFunction) {
  12446. this._activeRenderLoops = [];
  12447. return;
  12448. }
  12449. var index = this._activeRenderLoops.indexOf(renderFunction);
  12450. if (index >= 0) {
  12451. this._activeRenderLoops.splice(index, 1);
  12452. }
  12453. };
  12454. /** @ignore */
  12455. Engine.prototype._renderLoop = function () {
  12456. if (!this._contextWasLost) {
  12457. var shouldRender = true;
  12458. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12459. shouldRender = false;
  12460. }
  12461. if (shouldRender) {
  12462. // Start new frame
  12463. this.beginFrame();
  12464. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12465. var renderFunction = this._activeRenderLoops[index];
  12466. renderFunction();
  12467. }
  12468. // Present
  12469. this.endFrame();
  12470. }
  12471. }
  12472. if (this._activeRenderLoops.length > 0) {
  12473. // Register new frame
  12474. var requester = null;
  12475. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12476. requester = this._vrDisplay;
  12477. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12478. }
  12479. else {
  12480. this._renderingQueueLaunched = false;
  12481. }
  12482. };
  12483. /**
  12484. * Register and execute a render loop. The engine can have more than one render function
  12485. * @param renderFunction defines the function to continuously execute
  12486. */
  12487. Engine.prototype.runRenderLoop = function (renderFunction) {
  12488. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12489. return;
  12490. }
  12491. this._activeRenderLoops.push(renderFunction);
  12492. if (!this._renderingQueueLaunched) {
  12493. this._renderingQueueLaunched = true;
  12494. this._bindedRenderFunction = this._renderLoop.bind(this);
  12495. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12496. }
  12497. };
  12498. /**
  12499. * Toggle full screen mode
  12500. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12501. * @param options defines an option object to be sent to the requestFullscreen function
  12502. */
  12503. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12504. if (this.isFullscreen) {
  12505. BABYLON.Tools.ExitFullscreen();
  12506. }
  12507. else {
  12508. this._pointerLockRequested = requestPointerLock;
  12509. if (this._renderingCanvas) {
  12510. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12511. }
  12512. }
  12513. };
  12514. /**
  12515. * Clear the current render buffer or the current render target (if any is set up)
  12516. * @param color defines the color to use
  12517. * @param backBuffer defines if the back buffer must be cleared
  12518. * @param depth defines if the depth buffer must be cleared
  12519. * @param stencil defines if the stencil buffer must be cleared
  12520. */
  12521. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12522. if (stencil === void 0) { stencil = false; }
  12523. this.applyStates();
  12524. var mode = 0;
  12525. if (backBuffer && color) {
  12526. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12527. mode |= this._gl.COLOR_BUFFER_BIT;
  12528. }
  12529. if (depth) {
  12530. this._gl.clearDepth(1.0);
  12531. mode |= this._gl.DEPTH_BUFFER_BIT;
  12532. }
  12533. if (stencil) {
  12534. this._gl.clearStencil(0);
  12535. mode |= this._gl.STENCIL_BUFFER_BIT;
  12536. }
  12537. this._gl.clear(mode);
  12538. };
  12539. /**
  12540. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12541. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12542. * @param y defines the y-coordinate of the corner of the clear rectangle
  12543. * @param width defines the width of the clear rectangle
  12544. * @param height defines the height of the clear rectangle
  12545. * @param clearColor defines the clear color
  12546. */
  12547. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12548. var gl = this._gl;
  12549. // Save state
  12550. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12551. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12552. // Change state
  12553. gl.enable(gl.SCISSOR_TEST);
  12554. gl.scissor(x, y, width, height);
  12555. // Clear
  12556. this.clear(clearColor, true, true, true);
  12557. // Restore state
  12558. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12559. if (curScissor === true) {
  12560. gl.enable(gl.SCISSOR_TEST);
  12561. }
  12562. else {
  12563. gl.disable(gl.SCISSOR_TEST);
  12564. }
  12565. };
  12566. /**
  12567. * Set the WebGL's viewport
  12568. * @param viewport defines the viewport element to be used
  12569. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12570. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12571. */
  12572. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12573. var width = requiredWidth || this.getRenderWidth();
  12574. var height = requiredHeight || this.getRenderHeight();
  12575. var x = viewport.x || 0;
  12576. var y = viewport.y || 0;
  12577. this._cachedViewport = viewport;
  12578. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12579. };
  12580. /**
  12581. * Directly set the WebGL Viewport
  12582. * @param x defines the x coordinate of the viewport (in screen space)
  12583. * @param y defines the y coordinate of the viewport (in screen space)
  12584. * @param width defines the width of the viewport (in screen space)
  12585. * @param height defines the height of the viewport (in screen space)
  12586. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12587. */
  12588. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12589. var currentViewport = this._cachedViewport;
  12590. this._cachedViewport = null;
  12591. this._gl.viewport(x, y, width, height);
  12592. return currentViewport;
  12593. };
  12594. /**
  12595. * Begin a new frame
  12596. */
  12597. Engine.prototype.beginFrame = function () {
  12598. this.onBeginFrameObservable.notifyObservers(this);
  12599. this._measureFps();
  12600. };
  12601. /**
  12602. * Enf the current frame
  12603. */
  12604. Engine.prototype.endFrame = function () {
  12605. // Force a flush in case we are using a bad OS.
  12606. if (this._badOS) {
  12607. this.flushFramebuffer();
  12608. }
  12609. // Submit frame to the vr device, if enabled
  12610. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12611. // TODO: We should only submit the frame if we read frameData successfully.
  12612. this._vrDisplay.submitFrame();
  12613. }
  12614. this.onEndFrameObservable.notifyObservers(this);
  12615. };
  12616. /**
  12617. * Resize the view according to the canvas' size
  12618. */
  12619. Engine.prototype.resize = function () {
  12620. // We're not resizing the size of the canvas while in VR mode & presenting
  12621. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12622. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12623. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12624. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12625. }
  12626. };
  12627. /**
  12628. * Force a specific size of the canvas
  12629. * @param width defines the new canvas' width
  12630. * @param height defines the new canvas' height
  12631. */
  12632. Engine.prototype.setSize = function (width, height) {
  12633. if (!this._renderingCanvas) {
  12634. return;
  12635. }
  12636. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12637. return;
  12638. }
  12639. this._renderingCanvas.width = width;
  12640. this._renderingCanvas.height = height;
  12641. for (var index = 0; index < this.scenes.length; index++) {
  12642. var scene = this.scenes[index];
  12643. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12644. var cam = scene.cameras[camIndex];
  12645. cam._currentRenderId = 0;
  12646. }
  12647. }
  12648. if (this.onResizeObservable.hasObservers) {
  12649. this.onResizeObservable.notifyObservers(this);
  12650. }
  12651. };
  12652. // WebVR functions
  12653. /**
  12654. * Gets a boolean indicating if a webVR device was detected
  12655. * @returns true if a webVR device was detected
  12656. */
  12657. Engine.prototype.isVRDevicePresent = function () {
  12658. return !!this._vrDisplay;
  12659. };
  12660. /**
  12661. * Gets the current webVR device
  12662. * @returns the current webVR device (or null)
  12663. */
  12664. Engine.prototype.getVRDevice = function () {
  12665. return this._vrDisplay;
  12666. };
  12667. /**
  12668. * Initializes a webVR display and starts listening to display change events
  12669. * The onVRDisplayChangedObservable will be notified upon these changes
  12670. * @returns The onVRDisplayChangedObservable
  12671. */
  12672. Engine.prototype.initWebVR = function () {
  12673. this.initWebVRAsync();
  12674. return this.onVRDisplayChangedObservable;
  12675. };
  12676. /**
  12677. * Initializes a webVR display and starts listening to display change events
  12678. * The onVRDisplayChangedObservable will be notified upon these changes
  12679. * @returns A promise containing a VRDisplay and if vr is supported
  12680. */
  12681. Engine.prototype.initWebVRAsync = function () {
  12682. var _this = this;
  12683. var notifyObservers = function () {
  12684. var eventArgs = {
  12685. vrDisplay: _this._vrDisplay,
  12686. vrSupported: _this._vrSupported
  12687. };
  12688. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12689. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12690. };
  12691. if (!this._onVrDisplayConnect) {
  12692. this._onVrDisplayConnect = function (event) {
  12693. _this._vrDisplay = event.display;
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayDisconnect = function () {
  12697. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12698. _this._vrDisplay = undefined;
  12699. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12700. notifyObservers();
  12701. };
  12702. this._onVrDisplayPresentChange = function () {
  12703. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12704. };
  12705. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12706. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12708. }
  12709. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12710. this._webVRInitPromise.then(notifyObservers);
  12711. return this._webVRInitPromise;
  12712. };
  12713. /**
  12714. * Call this function to switch to webVR mode
  12715. * Will do nothing if webVR is not supported or if there is no webVR device
  12716. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12717. */
  12718. Engine.prototype.enableVR = function () {
  12719. var _this = this;
  12720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12721. var onResolved = function () {
  12722. _this.onVRRequestPresentComplete.notifyObservers(true);
  12723. _this._onVRFullScreenTriggered();
  12724. };
  12725. var onRejected = function () {
  12726. _this.onVRRequestPresentComplete.notifyObservers(false);
  12727. };
  12728. this.onVRRequestPresentStart.notifyObservers(this);
  12729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12730. }
  12731. };
  12732. /**
  12733. * Call this function to leave webVR mode
  12734. * Will do nothing if webVR is not supported or if there is no webVR device
  12735. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12736. */
  12737. Engine.prototype.disableVR = function () {
  12738. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12739. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12740. }
  12741. };
  12742. Engine.prototype._getVRDisplaysAsync = function () {
  12743. var _this = this;
  12744. return new Promise(function (res, rej) {
  12745. if (navigator.getVRDisplays) {
  12746. navigator.getVRDisplays().then(function (devices) {
  12747. _this._vrSupported = true;
  12748. // note that devices may actually be an empty array. This is fine;
  12749. // we expect this._vrDisplay to be undefined in this case.
  12750. _this._vrDisplay = devices[0];
  12751. res({
  12752. vrDisplay: _this._vrDisplay,
  12753. vrSupported: _this._vrSupported
  12754. });
  12755. });
  12756. }
  12757. else {
  12758. _this._vrDisplay = undefined;
  12759. _this._vrSupported = false;
  12760. res({
  12761. vrDisplay: _this._vrDisplay,
  12762. vrSupported: _this._vrSupported
  12763. });
  12764. }
  12765. });
  12766. };
  12767. /**
  12768. * Binds the frame buffer to the specified texture.
  12769. * @param texture The texture to render to or null for the default canvas
  12770. * @param faceIndex The face of the texture to render to in case of cube texture
  12771. * @param requiredWidth The width of the target to render to
  12772. * @param requiredHeight The height of the target to render to
  12773. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12774. * @param depthStencilTexture The depth stencil texture to use to render
  12775. */
  12776. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12777. if (this._currentRenderTarget) {
  12778. this.unBindFramebuffer(this._currentRenderTarget);
  12779. }
  12780. this._currentRenderTarget = texture;
  12781. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12782. var gl = this._gl;
  12783. if (texture.isCube) {
  12784. if (faceIndex === undefined) {
  12785. faceIndex = 0;
  12786. }
  12787. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12788. if (depthStencilTexture) {
  12789. if (depthStencilTexture._generateStencilBuffer) {
  12790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12791. }
  12792. else {
  12793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12794. }
  12795. }
  12796. }
  12797. if (this._cachedViewport && !forceFullscreenViewport) {
  12798. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12799. }
  12800. else {
  12801. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12802. }
  12803. this.wipeCaches();
  12804. };
  12805. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12806. if (this._currentFramebuffer !== framebuffer) {
  12807. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12808. this._currentFramebuffer = framebuffer;
  12809. }
  12810. };
  12811. /**
  12812. * Unbind the current render target texture from the webGL context
  12813. * @param texture defines the render target texture to unbind
  12814. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12815. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12816. */
  12817. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12818. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12819. this._currentRenderTarget = null;
  12820. // If MSAA, we need to bitblt back to main texture
  12821. var gl = this._gl;
  12822. if (texture._MSAAFramebuffer) {
  12823. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12824. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12825. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12826. }
  12827. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12828. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12829. gl.generateMipmap(gl.TEXTURE_2D);
  12830. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12831. }
  12832. if (onBeforeUnbind) {
  12833. if (texture._MSAAFramebuffer) {
  12834. // Bind the correct framebuffer
  12835. this.bindUnboundFramebuffer(texture._framebuffer);
  12836. }
  12837. onBeforeUnbind();
  12838. }
  12839. this.bindUnboundFramebuffer(null);
  12840. };
  12841. /**
  12842. * Unbind a list of render target textures from the webGL context
  12843. * This is used only when drawBuffer extension or webGL2 are active
  12844. * @param textures defines the render target textures to unbind
  12845. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12846. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12847. */
  12848. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12849. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12850. this._currentRenderTarget = null;
  12851. // If MSAA, we need to bitblt back to main texture
  12852. var gl = this._gl;
  12853. if (textures[0]._MSAAFramebuffer) {
  12854. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12855. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12856. var attachments = textures[0]._attachments;
  12857. if (!attachments) {
  12858. attachments = new Array(textures.length);
  12859. textures[0]._attachments = attachments;
  12860. }
  12861. for (var i = 0; i < textures.length; i++) {
  12862. var texture = textures[i];
  12863. for (var j = 0; j < attachments.length; j++) {
  12864. attachments[j] = gl.NONE;
  12865. }
  12866. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12867. gl.readBuffer(attachments[i]);
  12868. gl.drawBuffers(attachments);
  12869. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12870. }
  12871. for (var i = 0; i < attachments.length; i++) {
  12872. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12873. }
  12874. gl.drawBuffers(attachments);
  12875. }
  12876. for (var i = 0; i < textures.length; i++) {
  12877. var texture = textures[i];
  12878. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12879. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12880. gl.generateMipmap(gl.TEXTURE_2D);
  12881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12882. }
  12883. }
  12884. if (onBeforeUnbind) {
  12885. if (textures[0]._MSAAFramebuffer) {
  12886. // Bind the correct framebuffer
  12887. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12888. }
  12889. onBeforeUnbind();
  12890. }
  12891. this.bindUnboundFramebuffer(null);
  12892. };
  12893. /**
  12894. * Force the mipmap generation for the given render target texture
  12895. * @param texture defines the render target texture to use
  12896. */
  12897. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12898. if (texture.generateMipMaps) {
  12899. var gl = this._gl;
  12900. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12901. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12903. }
  12904. };
  12905. /**
  12906. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12907. */
  12908. Engine.prototype.flushFramebuffer = function () {
  12909. this._gl.flush();
  12910. };
  12911. /**
  12912. * Unbind the current render target and bind the default framebuffer
  12913. */
  12914. Engine.prototype.restoreDefaultFramebuffer = function () {
  12915. if (this._currentRenderTarget) {
  12916. this.unBindFramebuffer(this._currentRenderTarget);
  12917. }
  12918. else {
  12919. this.bindUnboundFramebuffer(null);
  12920. }
  12921. if (this._cachedViewport) {
  12922. this.setViewport(this._cachedViewport);
  12923. }
  12924. this.wipeCaches();
  12925. };
  12926. // UBOs
  12927. /**
  12928. * Create an uniform buffer
  12929. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12930. * @param elements defines the content of the uniform buffer
  12931. * @returns the webGL uniform buffer
  12932. */
  12933. Engine.prototype.createUniformBuffer = function (elements) {
  12934. var ubo = this._gl.createBuffer();
  12935. if (!ubo) {
  12936. throw new Error("Unable to create uniform buffer");
  12937. }
  12938. this.bindUniformBuffer(ubo);
  12939. if (elements instanceof Float32Array) {
  12940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12941. }
  12942. else {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12944. }
  12945. this.bindUniformBuffer(null);
  12946. ubo.references = 1;
  12947. return ubo;
  12948. };
  12949. /**
  12950. * Create a dynamic uniform buffer
  12951. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12952. * @param elements defines the content of the uniform buffer
  12953. * @returns the webGL uniform buffer
  12954. */
  12955. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12956. var ubo = this._gl.createBuffer();
  12957. if (!ubo) {
  12958. throw new Error("Unable to create dynamic uniform buffer");
  12959. }
  12960. this.bindUniformBuffer(ubo);
  12961. if (elements instanceof Float32Array) {
  12962. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12963. }
  12964. else {
  12965. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12966. }
  12967. this.bindUniformBuffer(null);
  12968. ubo.references = 1;
  12969. return ubo;
  12970. };
  12971. /**
  12972. * Update an existing uniform buffer
  12973. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12974. * @param uniformBuffer defines the target uniform buffer
  12975. * @param elements defines the content to update
  12976. * @param offset defines the offset in the uniform buffer where update should start
  12977. * @param count defines the size of the data to update
  12978. */
  12979. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12980. this.bindUniformBuffer(uniformBuffer);
  12981. if (offset === undefined) {
  12982. offset = 0;
  12983. }
  12984. if (count === undefined) {
  12985. if (elements instanceof Float32Array) {
  12986. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12987. }
  12988. else {
  12989. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12990. }
  12991. }
  12992. else {
  12993. if (elements instanceof Float32Array) {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12995. }
  12996. else {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12998. }
  12999. }
  13000. this.bindUniformBuffer(null);
  13001. };
  13002. // VBOs
  13003. Engine.prototype._resetVertexBufferBinding = function () {
  13004. this.bindArrayBuffer(null);
  13005. this._cachedVertexBuffers = null;
  13006. };
  13007. /**
  13008. * Creates a vertex buffer
  13009. * @param data the data for the vertex buffer
  13010. * @returns the new WebGL static buffer
  13011. */
  13012. Engine.prototype.createVertexBuffer = function (data) {
  13013. var vbo = this._gl.createBuffer();
  13014. if (!vbo) {
  13015. throw new Error("Unable to create vertex buffer");
  13016. }
  13017. this.bindArrayBuffer(vbo);
  13018. if (data instanceof Array) {
  13019. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13020. }
  13021. else {
  13022. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13023. }
  13024. this._resetVertexBufferBinding();
  13025. vbo.references = 1;
  13026. return vbo;
  13027. };
  13028. /**
  13029. * Creates a dynamic vertex buffer
  13030. * @param data the data for the dynamic vertex buffer
  13031. * @returns the new WebGL dynamic buffer
  13032. */
  13033. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13034. var vbo = this._gl.createBuffer();
  13035. if (!vbo) {
  13036. throw new Error("Unable to create dynamic vertex buffer");
  13037. }
  13038. this.bindArrayBuffer(vbo);
  13039. if (data instanceof Array) {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13044. }
  13045. this._resetVertexBufferBinding();
  13046. vbo.references = 1;
  13047. return vbo;
  13048. };
  13049. /**
  13050. * Update a dynamic index buffer
  13051. * @param indexBuffer defines the target index buffer
  13052. * @param indices defines the data to update
  13053. * @param offset defines the offset in the target index buffer where update should start
  13054. */
  13055. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13056. if (offset === void 0) { offset = 0; }
  13057. // Force cache update
  13058. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13059. this.bindIndexBuffer(indexBuffer);
  13060. var arrayBuffer;
  13061. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13062. arrayBuffer = indices;
  13063. }
  13064. else {
  13065. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13066. }
  13067. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13068. this._resetIndexBufferBinding();
  13069. };
  13070. /**
  13071. * Updates a dynamic vertex buffer.
  13072. * @param vertexBuffer the vertex buffer to update
  13073. * @param data the data used to update the vertex buffer
  13074. * @param byteOffset the byte offset of the data
  13075. * @param byteLength the byte length of the data
  13076. */
  13077. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13078. this.bindArrayBuffer(vertexBuffer);
  13079. if (byteOffset === undefined) {
  13080. byteOffset = 0;
  13081. }
  13082. if (byteLength === undefined) {
  13083. if (data instanceof Array) {
  13084. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13085. }
  13086. else {
  13087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13088. }
  13089. }
  13090. else {
  13091. if (data instanceof Array) {
  13092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13093. }
  13094. else {
  13095. if (data instanceof ArrayBuffer) {
  13096. data = new Uint8Array(data, byteOffset, byteLength);
  13097. }
  13098. else {
  13099. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13100. }
  13101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13102. }
  13103. }
  13104. this._resetVertexBufferBinding();
  13105. };
  13106. Engine.prototype._resetIndexBufferBinding = function () {
  13107. this.bindIndexBuffer(null);
  13108. this._cachedIndexBuffer = null;
  13109. };
  13110. /**
  13111. * Creates a new index buffer
  13112. * @param indices defines the content of the index buffer
  13113. * @param updatable defines if the index buffer must be updatable
  13114. * @returns a new webGL buffer
  13115. */
  13116. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13117. var vbo = this._gl.createBuffer();
  13118. if (!vbo) {
  13119. throw new Error("Unable to create index buffer");
  13120. }
  13121. this.bindIndexBuffer(vbo);
  13122. // Check for 32 bits indices
  13123. var arrayBuffer;
  13124. var need32Bits = false;
  13125. if (indices instanceof Uint16Array) {
  13126. arrayBuffer = indices;
  13127. }
  13128. else {
  13129. //check 32 bit support
  13130. if (this._caps.uintIndices) {
  13131. if (indices instanceof Uint32Array) {
  13132. arrayBuffer = indices;
  13133. need32Bits = true;
  13134. }
  13135. else {
  13136. //number[] or Int32Array, check if 32 bit is necessary
  13137. for (var index = 0; index < indices.length; index++) {
  13138. if (indices[index] > 65535) {
  13139. need32Bits = true;
  13140. break;
  13141. }
  13142. }
  13143. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13144. }
  13145. }
  13146. else {
  13147. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13148. arrayBuffer = new Uint16Array(indices);
  13149. }
  13150. }
  13151. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13152. this._resetIndexBufferBinding();
  13153. vbo.references = 1;
  13154. vbo.is32Bits = need32Bits;
  13155. return vbo;
  13156. };
  13157. /**
  13158. * Bind a webGL buffer to the webGL context
  13159. * @param buffer defines the buffer to bind
  13160. */
  13161. Engine.prototype.bindArrayBuffer = function (buffer) {
  13162. if (!this._vaoRecordInProgress) {
  13163. this._unbindVertexArrayObject();
  13164. }
  13165. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13166. };
  13167. /**
  13168. * Bind an uniform buffer to the current webGL context
  13169. * @param buffer defines the buffer to bind
  13170. */
  13171. Engine.prototype.bindUniformBuffer = function (buffer) {
  13172. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13173. };
  13174. /**
  13175. * Bind a buffer to the current webGL context at a given location
  13176. * @param buffer defines the buffer to bind
  13177. * @param location defines the index where to bind the buffer
  13178. */
  13179. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13180. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13181. };
  13182. /**
  13183. * Bind a specific block at a given index in a specific shader program
  13184. * @param shaderProgram defines the shader program
  13185. * @param blockName defines the block name
  13186. * @param index defines the index where to bind the block
  13187. */
  13188. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13189. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13190. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13191. };
  13192. ;
  13193. Engine.prototype.bindIndexBuffer = function (buffer) {
  13194. if (!this._vaoRecordInProgress) {
  13195. this._unbindVertexArrayObject();
  13196. }
  13197. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13198. };
  13199. Engine.prototype.bindBuffer = function (buffer, target) {
  13200. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13201. this._gl.bindBuffer(target, buffer);
  13202. this._currentBoundBuffer[target] = buffer;
  13203. }
  13204. };
  13205. /**
  13206. * update the bound buffer with the given data
  13207. * @param data defines the data to update
  13208. */
  13209. Engine.prototype.updateArrayBuffer = function (data) {
  13210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13211. };
  13212. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13213. var pointer = this._currentBufferPointers[indx];
  13214. var changed = false;
  13215. if (!pointer.active) {
  13216. changed = true;
  13217. pointer.active = true;
  13218. pointer.index = indx;
  13219. pointer.size = size;
  13220. pointer.type = type;
  13221. pointer.normalized = normalized;
  13222. pointer.stride = stride;
  13223. pointer.offset = offset;
  13224. pointer.buffer = buffer;
  13225. }
  13226. else {
  13227. if (pointer.buffer !== buffer) {
  13228. pointer.buffer = buffer;
  13229. changed = true;
  13230. }
  13231. if (pointer.size !== size) {
  13232. pointer.size = size;
  13233. changed = true;
  13234. }
  13235. if (pointer.type !== type) {
  13236. pointer.type = type;
  13237. changed = true;
  13238. }
  13239. if (pointer.normalized !== normalized) {
  13240. pointer.normalized = normalized;
  13241. changed = true;
  13242. }
  13243. if (pointer.stride !== stride) {
  13244. pointer.stride = stride;
  13245. changed = true;
  13246. }
  13247. if (pointer.offset !== offset) {
  13248. pointer.offset = offset;
  13249. changed = true;
  13250. }
  13251. }
  13252. if (changed || this._vaoRecordInProgress) {
  13253. this.bindArrayBuffer(buffer);
  13254. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13255. }
  13256. };
  13257. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13258. if (indexBuffer == null) {
  13259. return;
  13260. }
  13261. if (this._cachedIndexBuffer !== indexBuffer) {
  13262. this._cachedIndexBuffer = indexBuffer;
  13263. this.bindIndexBuffer(indexBuffer);
  13264. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13265. }
  13266. };
  13267. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13268. var attributes = effect.getAttributesNames();
  13269. if (!this._vaoRecordInProgress) {
  13270. this._unbindVertexArrayObject();
  13271. }
  13272. this.unbindAllAttributes();
  13273. for (var index = 0; index < attributes.length; index++) {
  13274. var order = effect.getAttributeLocation(index);
  13275. if (order >= 0) {
  13276. var vertexBuffer = vertexBuffers[attributes[index]];
  13277. if (!vertexBuffer) {
  13278. continue;
  13279. }
  13280. this._gl.enableVertexAttribArray(order);
  13281. if (!this._vaoRecordInProgress) {
  13282. this._vertexAttribArraysEnabled[order] = true;
  13283. }
  13284. var buffer = vertexBuffer.getBuffer();
  13285. if (buffer) {
  13286. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13287. if (vertexBuffer.getIsInstanced()) {
  13288. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13289. if (!this._vaoRecordInProgress) {
  13290. this._currentInstanceLocations.push(order);
  13291. this._currentInstanceBuffers.push(buffer);
  13292. }
  13293. }
  13294. }
  13295. }
  13296. }
  13297. };
  13298. /**
  13299. * Records a vertex array object
  13300. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13301. * @param vertexBuffers defines the list of vertex buffers to store
  13302. * @param indexBuffer defines the index buffer to store
  13303. * @param effect defines the effect to store
  13304. * @returns the new vertex array object
  13305. */
  13306. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13307. var vao = this._gl.createVertexArray();
  13308. this._vaoRecordInProgress = true;
  13309. this._gl.bindVertexArray(vao);
  13310. this._mustWipeVertexAttributes = true;
  13311. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13312. this.bindIndexBuffer(indexBuffer);
  13313. this._vaoRecordInProgress = false;
  13314. this._gl.bindVertexArray(null);
  13315. return vao;
  13316. };
  13317. /**
  13318. * Bind a specific vertex array object
  13319. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13320. * @param vertexArrayObject defines the vertex array object to bind
  13321. * @param indexBuffer defines the index buffer to bind
  13322. */
  13323. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13324. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13325. this._cachedVertexArrayObject = vertexArrayObject;
  13326. this._gl.bindVertexArray(vertexArrayObject);
  13327. this._cachedVertexBuffers = null;
  13328. this._cachedIndexBuffer = null;
  13329. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13330. this._mustWipeVertexAttributes = true;
  13331. }
  13332. };
  13333. /**
  13334. * Bind webGl buffers directly to the webGL context
  13335. * @param vertexBuffer defines the vertex buffer to bind
  13336. * @param indexBuffer defines the index buffer to bind
  13337. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13338. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13339. * @param effect defines the effect associated with the vertex buffer
  13340. */
  13341. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13342. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13343. this._cachedVertexBuffers = vertexBuffer;
  13344. this._cachedEffectForVertexBuffers = effect;
  13345. var attributesCount = effect.getAttributesCount();
  13346. this._unbindVertexArrayObject();
  13347. this.unbindAllAttributes();
  13348. var offset = 0;
  13349. for (var index = 0; index < attributesCount; index++) {
  13350. if (index < vertexDeclaration.length) {
  13351. var order = effect.getAttributeLocation(index);
  13352. if (order >= 0) {
  13353. this._gl.enableVertexAttribArray(order);
  13354. this._vertexAttribArraysEnabled[order] = true;
  13355. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13356. }
  13357. offset += vertexDeclaration[index] * 4;
  13358. }
  13359. }
  13360. }
  13361. this._bindIndexBufferWithCache(indexBuffer);
  13362. };
  13363. Engine.prototype._unbindVertexArrayObject = function () {
  13364. if (!this._cachedVertexArrayObject) {
  13365. return;
  13366. }
  13367. this._cachedVertexArrayObject = null;
  13368. this._gl.bindVertexArray(null);
  13369. };
  13370. /**
  13371. * Bind a list of vertex buffers to the webGL context
  13372. * @param vertexBuffers defines the list of vertex buffers to bind
  13373. * @param indexBuffer defines the index buffer to bind
  13374. * @param effect defines the effect associated with the vertex buffers
  13375. */
  13376. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13377. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13378. this._cachedVertexBuffers = vertexBuffers;
  13379. this._cachedEffectForVertexBuffers = effect;
  13380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13381. }
  13382. this._bindIndexBufferWithCache(indexBuffer);
  13383. };
  13384. /**
  13385. * Unbind all instance attributes
  13386. */
  13387. Engine.prototype.unbindInstanceAttributes = function () {
  13388. var boundBuffer;
  13389. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13390. var instancesBuffer = this._currentInstanceBuffers[i];
  13391. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13392. boundBuffer = instancesBuffer;
  13393. this.bindArrayBuffer(instancesBuffer);
  13394. }
  13395. var offsetLocation = this._currentInstanceLocations[i];
  13396. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13397. }
  13398. this._currentInstanceBuffers.length = 0;
  13399. this._currentInstanceLocations.length = 0;
  13400. };
  13401. /**
  13402. * Release and free the memory of a vertex array object
  13403. * @param vao defines the vertex array object to delete
  13404. */
  13405. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13406. this._gl.deleteVertexArray(vao);
  13407. };
  13408. /** @ignore */
  13409. Engine.prototype._releaseBuffer = function (buffer) {
  13410. buffer.references--;
  13411. if (buffer.references === 0) {
  13412. this._gl.deleteBuffer(buffer);
  13413. return true;
  13414. }
  13415. return false;
  13416. };
  13417. /**
  13418. * Creates a webGL buffer to use with instanciation
  13419. * @param capacity defines the size of the buffer
  13420. * @returns the webGL buffer
  13421. */
  13422. Engine.prototype.createInstancesBuffer = function (capacity) {
  13423. var buffer = this._gl.createBuffer();
  13424. if (!buffer) {
  13425. throw new Error("Unable to create instance buffer");
  13426. }
  13427. buffer.capacity = capacity;
  13428. this.bindArrayBuffer(buffer);
  13429. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13430. return buffer;
  13431. };
  13432. /**
  13433. * Delete a webGL buffer used with instanciation
  13434. * @param buffer defines the webGL buffer to delete
  13435. */
  13436. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13437. this._gl.deleteBuffer(buffer);
  13438. };
  13439. /**
  13440. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13441. * @param instancesBuffer defines the webGL buffer to update and bind
  13442. * @param data defines the data to store in the buffer
  13443. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13444. */
  13445. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13446. this.bindArrayBuffer(instancesBuffer);
  13447. if (data) {
  13448. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13449. }
  13450. if (offsetLocations[0].index !== undefined) {
  13451. var stride = 0;
  13452. for (var i = 0; i < offsetLocations.length; i++) {
  13453. var ai = offsetLocations[i];
  13454. stride += ai.attributeSize * 4;
  13455. }
  13456. for (var i = 0; i < offsetLocations.length; i++) {
  13457. var ai = offsetLocations[i];
  13458. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13459. this._gl.enableVertexAttribArray(ai.index);
  13460. this._vertexAttribArraysEnabled[ai.index] = true;
  13461. }
  13462. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13463. this._gl.vertexAttribDivisor(ai.index, 1);
  13464. this._currentInstanceLocations.push(ai.index);
  13465. this._currentInstanceBuffers.push(instancesBuffer);
  13466. }
  13467. }
  13468. else {
  13469. for (var index = 0; index < 4; index++) {
  13470. var offsetLocation = offsetLocations[index];
  13471. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13472. this._gl.enableVertexAttribArray(offsetLocation);
  13473. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13474. }
  13475. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13476. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13477. this._currentInstanceLocations.push(offsetLocation);
  13478. this._currentInstanceBuffers.push(instancesBuffer);
  13479. }
  13480. }
  13481. };
  13482. /**
  13483. * Apply all cached states (depth, culling, stencil and alpha)
  13484. */
  13485. Engine.prototype.applyStates = function () {
  13486. this._depthCullingState.apply(this._gl);
  13487. this._stencilState.apply(this._gl);
  13488. this._alphaState.apply(this._gl);
  13489. };
  13490. /**
  13491. * Send a draw order
  13492. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13493. * @param indexStart defines the starting index
  13494. * @param indexCount defines the number of index to draw
  13495. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13496. */
  13497. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13498. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13499. };
  13500. /**
  13501. * Draw a list of points
  13502. * @param verticesStart defines the index of first vertex to draw
  13503. * @param verticesCount defines the count of vertices to draw
  13504. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13505. */
  13506. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13507. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13508. };
  13509. /**
  13510. * Draw a list of unindexed primitives
  13511. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13512. * @param verticesStart defines the index of first vertex to draw
  13513. * @param verticesCount defines the count of vertices to draw
  13514. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13515. */
  13516. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13517. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13518. };
  13519. /**
  13520. * Draw a list of indexed primitives
  13521. * @param fillMode defines the primitive to use
  13522. * @param indexStart defines the starting index
  13523. * @param indexCount defines the number of index to draw
  13524. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13525. */
  13526. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13527. // Apply states
  13528. this.applyStates();
  13529. this._drawCalls.addCount(1, false);
  13530. // Render
  13531. var drawMode = this._drawMode(fillMode);
  13532. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13533. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13534. if (instancesCount) {
  13535. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13536. }
  13537. else {
  13538. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13539. }
  13540. };
  13541. /**
  13542. * Draw a list of unindexed primitives
  13543. * @param fillMode defines the primitive to use
  13544. * @param verticesStart defines the index of first vertex to draw
  13545. * @param verticesCount defines the count of vertices to draw
  13546. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13547. */
  13548. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13549. // Apply states
  13550. this.applyStates();
  13551. this._drawCalls.addCount(1, false);
  13552. var drawMode = this._drawMode(fillMode);
  13553. if (instancesCount) {
  13554. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13555. }
  13556. else {
  13557. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13558. }
  13559. };
  13560. Engine.prototype._drawMode = function (fillMode) {
  13561. switch (fillMode) {
  13562. // Triangle views
  13563. case BABYLON.Material.TriangleFillMode:
  13564. return this._gl.TRIANGLES;
  13565. case BABYLON.Material.PointFillMode:
  13566. return this._gl.POINTS;
  13567. case BABYLON.Material.WireFrameFillMode:
  13568. return this._gl.LINES;
  13569. // Draw modes
  13570. case BABYLON.Material.PointListDrawMode:
  13571. return this._gl.POINTS;
  13572. case BABYLON.Material.LineListDrawMode:
  13573. return this._gl.LINES;
  13574. case BABYLON.Material.LineLoopDrawMode:
  13575. return this._gl.LINE_LOOP;
  13576. case BABYLON.Material.LineStripDrawMode:
  13577. return this._gl.LINE_STRIP;
  13578. case BABYLON.Material.TriangleStripDrawMode:
  13579. return this._gl.TRIANGLE_STRIP;
  13580. case BABYLON.Material.TriangleFanDrawMode:
  13581. return this._gl.TRIANGLE_FAN;
  13582. default:
  13583. return this._gl.TRIANGLES;
  13584. }
  13585. };
  13586. // Shaders
  13587. /** @ignore */
  13588. Engine.prototype._releaseEffect = function (effect) {
  13589. if (this._compiledEffects[effect._key]) {
  13590. delete this._compiledEffects[effect._key];
  13591. this._deleteProgram(effect.getProgram());
  13592. }
  13593. };
  13594. /** @ignore */
  13595. Engine.prototype._deleteProgram = function (program) {
  13596. if (program) {
  13597. program.__SPECTOR_rebuildProgram = null;
  13598. if (program.transformFeedback) {
  13599. this.deleteTransformFeedback(program.transformFeedback);
  13600. program.transformFeedback = null;
  13601. }
  13602. this._gl.deleteProgram(program);
  13603. }
  13604. };
  13605. /**
  13606. * Create a new effect (used to store vertex/fragment shaders)
  13607. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13608. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13609. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13610. * @param samplers defines an array of string used to represent textures
  13611. * @param defines defines the string containing the defines to use to compile the shaders
  13612. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13613. * @param onCompiled defines a function to call when the effect creation is successful
  13614. * @param onError defines a function to call when the effect creation has failed
  13615. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13616. * @returns the new Effect
  13617. */
  13618. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13619. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13620. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13621. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13622. if (this._compiledEffects[name]) {
  13623. var compiledEffect = this._compiledEffects[name];
  13624. if (onCompiled && compiledEffect.isReady()) {
  13625. onCompiled(compiledEffect);
  13626. }
  13627. return compiledEffect;
  13628. }
  13629. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13630. effect._key = name;
  13631. this._compiledEffects[name] = effect;
  13632. return effect;
  13633. };
  13634. /**
  13635. * Create an effect to use with particle systems
  13636. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13637. * @param uniformsNames defines a list of attribute names
  13638. * @param samplers defines an array of string used to represent textures
  13639. * @param defines defines the string containing the defines to use to compile the shaders
  13640. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13641. * @param onCompiled defines a function to call when the effect creation is successful
  13642. * @param onError defines a function to call when the effect creation has failed
  13643. * @returns the new Effect
  13644. */
  13645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13646. if (uniformsNames === void 0) { uniformsNames = []; }
  13647. if (samplers === void 0) { samplers = []; }
  13648. if (defines === void 0) { defines = ""; }
  13649. return this.createEffect({
  13650. vertex: "particles",
  13651. fragmentElement: fragmentName
  13652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13653. };
  13654. /**
  13655. * Directly creates a webGL program
  13656. * @param vertexCode defines the vertex shader code to use
  13657. * @param fragmentCode defines the fragment shader code to use
  13658. * @param context defines the webGL context to use (if not set, the current one will be used)
  13659. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13660. * @returns the new webGL program
  13661. */
  13662. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13663. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13664. context = context || this._gl;
  13665. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13666. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13667. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13668. };
  13669. /**
  13670. * Creates a webGL program
  13671. * @param vertexCode defines the vertex shader code to use
  13672. * @param fragmentCode defines the fragment shader code to use
  13673. * @param defines defines the string containing the defines to use to compile the shaders
  13674. * @param context defines the webGL context to use (if not set, the current one will be used)
  13675. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13676. * @returns the new webGL program
  13677. */
  13678. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13679. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13680. context = context || this._gl;
  13681. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13682. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13683. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13684. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13685. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13686. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13687. return program;
  13688. };
  13689. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13690. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13691. var shaderProgram = context.createProgram();
  13692. if (!shaderProgram) {
  13693. throw new Error("Unable to create program");
  13694. }
  13695. context.attachShader(shaderProgram, vertexShader);
  13696. context.attachShader(shaderProgram, fragmentShader);
  13697. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13698. var transformFeedback = this.createTransformFeedback();
  13699. this.bindTransformFeedback(transformFeedback);
  13700. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13701. shaderProgram.transformFeedback = transformFeedback;
  13702. }
  13703. context.linkProgram(shaderProgram);
  13704. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13705. this.bindTransformFeedback(null);
  13706. }
  13707. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13708. if (!linked) {
  13709. context.validateProgram(shaderProgram);
  13710. var error = context.getProgramInfoLog(shaderProgram);
  13711. if (error) {
  13712. throw new Error(error);
  13713. }
  13714. }
  13715. context.deleteShader(vertexShader);
  13716. context.deleteShader(fragmentShader);
  13717. return shaderProgram;
  13718. };
  13719. /**
  13720. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13721. * @param shaderProgram defines the webGL program to use
  13722. * @param uniformsNames defines the list of uniform names
  13723. * @returns an array of webGL uniform locations
  13724. */
  13725. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13726. var results = new Array();
  13727. for (var index = 0; index < uniformsNames.length; index++) {
  13728. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13729. }
  13730. return results;
  13731. };
  13732. /**
  13733. * Gets the lsit of active attributes for a given webGL program
  13734. * @param shaderProgram defines the webGL program to use
  13735. * @param attributesNames defines the list of attribute names to get
  13736. * @returns an array of indices indicating the offset of each attribute
  13737. */
  13738. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13739. var results = [];
  13740. for (var index = 0; index < attributesNames.length; index++) {
  13741. try {
  13742. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13743. }
  13744. catch (e) {
  13745. results.push(-1);
  13746. }
  13747. }
  13748. return results;
  13749. };
  13750. /**
  13751. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13752. * @param effect defines the effect to activate
  13753. */
  13754. Engine.prototype.enableEffect = function (effect) {
  13755. if (!effect) {
  13756. return;
  13757. }
  13758. // Use program
  13759. this.bindSamplers(effect);
  13760. this._currentEffect = effect;
  13761. if (effect.onBind) {
  13762. effect.onBind(effect);
  13763. }
  13764. effect.onBindObservable.notifyObservers(effect);
  13765. };
  13766. /**
  13767. * Set the value of an uniform to an array of int32
  13768. * @param uniform defines the webGL uniform location where to store the value
  13769. * @param array defines the array of int32 to store
  13770. */
  13771. Engine.prototype.setIntArray = function (uniform, array) {
  13772. if (!uniform)
  13773. return;
  13774. this._gl.uniform1iv(uniform, array);
  13775. };
  13776. /**
  13777. * Set the value of an uniform to an array of int32 (stored as vec2)
  13778. * @param uniform defines the webGL uniform location where to store the value
  13779. * @param array defines the array of int32 to store
  13780. */
  13781. Engine.prototype.setIntArray2 = function (uniform, array) {
  13782. if (!uniform || array.length % 2 !== 0)
  13783. return;
  13784. this._gl.uniform2iv(uniform, array);
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of int32 (stored as vec3)
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of int32 to store
  13790. */
  13791. Engine.prototype.setIntArray3 = function (uniform, array) {
  13792. if (!uniform || array.length % 3 !== 0)
  13793. return;
  13794. this._gl.uniform3iv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of int32 (stored as vec4)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of int32 to store
  13800. */
  13801. Engine.prototype.setIntArray4 = function (uniform, array) {
  13802. if (!uniform || array.length % 4 !== 0)
  13803. return;
  13804. this._gl.uniform4iv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of float32
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of float32 to store
  13810. */
  13811. Engine.prototype.setFloatArray = function (uniform, array) {
  13812. if (!uniform)
  13813. return;
  13814. this._gl.uniform1fv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of float32 (stored as vec2)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of float32 to store
  13820. */
  13821. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13822. if (!uniform || array.length % 2 !== 0)
  13823. return;
  13824. this._gl.uniform2fv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32 (stored as vec3)
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13832. if (!uniform || array.length % 3 !== 0)
  13833. return;
  13834. this._gl.uniform3fv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of float32 (stored as vec4)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of float32 to store
  13840. */
  13841. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13842. if (!uniform || array.length % 4 !== 0)
  13843. return;
  13844. this._gl.uniform4fv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of number
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of number to store
  13850. */
  13851. Engine.prototype.setArray = function (uniform, array) {
  13852. if (!uniform)
  13853. return;
  13854. this._gl.uniform1fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of number (stored as vec2)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of number to store
  13860. */
  13861. Engine.prototype.setArray2 = function (uniform, array) {
  13862. if (!uniform || array.length % 2 !== 0)
  13863. return;
  13864. this._gl.uniform2fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of number (stored as vec3)
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of number to store
  13870. */
  13871. Engine.prototype.setArray3 = function (uniform, array) {
  13872. if (!uniform || array.length % 3 !== 0)
  13873. return;
  13874. this._gl.uniform3fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of number (stored as vec4)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of number to store
  13880. */
  13881. Engine.prototype.setArray4 = function (uniform, array) {
  13882. if (!uniform || array.length % 4 !== 0)
  13883. return;
  13884. this._gl.uniform4fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of float32 (stored as matrices)
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param matrices defines the array of float32 to store
  13890. */
  13891. Engine.prototype.setMatrices = function (uniform, matrices) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a matrix
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param matrix defines the matrix to store
  13900. */
  13901. Engine.prototype.setMatrix = function (uniform, matrix) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a matrix (3x3)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13910. */
  13911. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to a matrix (2x2)
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13920. */
  13921. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13922. if (!uniform)
  13923. return;
  13924. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13925. };
  13926. /**
  13927. * Set the value of an uniform to a number (int)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param value defines the int number to store
  13930. */
  13931. Engine.prototype.setInt = function (uniform, value) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniform1i(uniform, value);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a number (float)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param value defines the float number to store
  13940. */
  13941. Engine.prototype.setFloat = function (uniform, value) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniform1f(uniform, value);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a vec2
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param x defines the 1st component of the value
  13950. * @param y defines the 2nd component of the value
  13951. */
  13952. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13953. if (!uniform)
  13954. return;
  13955. this._gl.uniform2f(uniform, x, y);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to a vec3
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param x defines the 1st component of the value
  13961. * @param y defines the 2nd component of the value
  13962. * @param z defines the 3rd component of the value
  13963. */
  13964. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform3f(uniform, x, y, z);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a boolean
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param bool defines the boolean to store
  13973. */
  13974. Engine.prototype.setBool = function (uniform, bool) {
  13975. if (!uniform)
  13976. return;
  13977. this._gl.uniform1i(uniform, bool);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to a vec4
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param x defines the 1st component of the value
  13983. * @param y defines the 2nd component of the value
  13984. * @param z defines the 3rd component of the value
  13985. * @param w defines the 4th component of the value
  13986. */
  13987. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform4f(uniform, x, y, z, w);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a Color3
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param color3 defines the color to store
  13996. */
  13997. Engine.prototype.setColor3 = function (uniform, color3) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a Color3 and an alpha value
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param color3 defines the color to store
  14006. * @param alpha defines the alpha component to store
  14007. */
  14008. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14012. };
  14013. /**
  14014. * Sets a Color4 on a uniform variable
  14015. * @param uniform defines the uniform location
  14016. * @param color4 defines the value to be set
  14017. */
  14018. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14019. if (!uniform)
  14020. return;
  14021. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14022. };
  14023. // States
  14024. /**
  14025. * Set various states to the webGL context
  14026. * @param culling defines backface culling state
  14027. * @param zOffset defines the value to apply to zOffset (0 by default)
  14028. * @param force defines if states must be applied even if cache is up to date
  14029. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14030. */
  14031. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14032. if (zOffset === void 0) { zOffset = 0; }
  14033. if (reverseSide === void 0) { reverseSide = false; }
  14034. // Culling
  14035. if (this._depthCullingState.cull !== culling || force) {
  14036. this._depthCullingState.cull = culling;
  14037. }
  14038. // Cull face
  14039. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14040. if (this._depthCullingState.cullFace !== cullFace || force) {
  14041. this._depthCullingState.cullFace = cullFace;
  14042. }
  14043. // Z offset
  14044. this.setZOffset(zOffset);
  14045. // Front face
  14046. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14047. if (this._depthCullingState.frontFace !== frontFace || force) {
  14048. this._depthCullingState.frontFace = frontFace;
  14049. }
  14050. };
  14051. /**
  14052. * Set the z offset to apply to current rendering
  14053. * @param value defines the offset to apply
  14054. */
  14055. Engine.prototype.setZOffset = function (value) {
  14056. this._depthCullingState.zOffset = value;
  14057. };
  14058. /**
  14059. * Gets the current value of the zOffset
  14060. * @returns the current zOffset state
  14061. */
  14062. Engine.prototype.getZOffset = function () {
  14063. return this._depthCullingState.zOffset;
  14064. };
  14065. /**
  14066. * Enable or disable depth buffering
  14067. * @param enable defines the state to set
  14068. */
  14069. Engine.prototype.setDepthBuffer = function (enable) {
  14070. this._depthCullingState.depthTest = enable;
  14071. };
  14072. /**
  14073. * Gets a boolean indicating if depth writing is enabled
  14074. * @returns the current depth writing state
  14075. */
  14076. Engine.prototype.getDepthWrite = function () {
  14077. return this._depthCullingState.depthMask;
  14078. };
  14079. /**
  14080. * Enable or disable depth writing
  14081. * @param enable defines the state to set
  14082. */
  14083. Engine.prototype.setDepthWrite = function (enable) {
  14084. this._depthCullingState.depthMask = enable;
  14085. };
  14086. /**
  14087. * Enable or disable color writing
  14088. * @param enable defines the state to set
  14089. */
  14090. Engine.prototype.setColorWrite = function (enable) {
  14091. this._gl.colorMask(enable, enable, enable, enable);
  14092. this._colorWrite = enable;
  14093. };
  14094. /**
  14095. * Gets a boolean indicating if color writing is enabled
  14096. * @returns the current color writing state
  14097. */
  14098. Engine.prototype.getColorWrite = function () {
  14099. return this._colorWrite;
  14100. };
  14101. /**
  14102. * Sets alpha constants used by some alpha blending modes
  14103. * @param r defines the red component
  14104. * @param g defines the green component
  14105. * @param b defines the blue component
  14106. * @param a defines the alpha component
  14107. */
  14108. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14109. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14110. };
  14111. /**
  14112. * Sets the current alpha mode
  14113. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14114. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14115. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14116. */
  14117. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14118. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14119. if (this._alphaMode === mode) {
  14120. return;
  14121. }
  14122. switch (mode) {
  14123. case Engine.ALPHA_DISABLE:
  14124. this._alphaState.alphaBlend = false;
  14125. break;
  14126. case Engine.ALPHA_PREMULTIPLIED:
  14127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14128. this._alphaState.alphaBlend = true;
  14129. break;
  14130. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14132. this._alphaState.alphaBlend = true;
  14133. break;
  14134. case Engine.ALPHA_COMBINE:
  14135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14136. this._alphaState.alphaBlend = true;
  14137. break;
  14138. case Engine.ALPHA_ONEONE:
  14139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14140. this._alphaState.alphaBlend = true;
  14141. break;
  14142. case Engine.ALPHA_ADD:
  14143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14144. this._alphaState.alphaBlend = true;
  14145. break;
  14146. case Engine.ALPHA_SUBTRACT:
  14147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14148. this._alphaState.alphaBlend = true;
  14149. break;
  14150. case Engine.ALPHA_MULTIPLY:
  14151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14152. this._alphaState.alphaBlend = true;
  14153. break;
  14154. case Engine.ALPHA_MAXIMIZED:
  14155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14156. this._alphaState.alphaBlend = true;
  14157. break;
  14158. case Engine.ALPHA_INTERPOLATE:
  14159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14160. this._alphaState.alphaBlend = true;
  14161. break;
  14162. case Engine.ALPHA_SCREENMODE:
  14163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14164. this._alphaState.alphaBlend = true;
  14165. break;
  14166. }
  14167. if (!noDepthWriteChange) {
  14168. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14169. }
  14170. this._alphaMode = mode;
  14171. };
  14172. /**
  14173. * Gets the current alpha mode
  14174. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14175. * @returns the current alpha mode
  14176. */
  14177. Engine.prototype.getAlphaMode = function () {
  14178. return this._alphaMode;
  14179. };
  14180. // Textures
  14181. /**
  14182. * Force the entire cache to be cleared
  14183. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14184. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14185. */
  14186. Engine.prototype.wipeCaches = function (bruteForce) {
  14187. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14188. return;
  14189. }
  14190. this._currentEffect = null;
  14191. if (bruteForce) {
  14192. this.resetTextureCache();
  14193. this._currentProgram = null;
  14194. this._stencilState.reset();
  14195. this._depthCullingState.reset();
  14196. this.setDepthFunctionToLessOrEqual();
  14197. this._alphaState.reset();
  14198. }
  14199. this._resetVertexBufferBinding();
  14200. this._cachedIndexBuffer = null;
  14201. this._cachedEffectForVertexBuffers = null;
  14202. this._unbindVertexArrayObject();
  14203. this.bindIndexBuffer(null);
  14204. };
  14205. /**
  14206. * Set the compressed texture format to use, based on the formats you have, and the formats
  14207. * supported by the hardware / browser.
  14208. *
  14209. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14210. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14211. * to API arguments needed to compressed textures. This puts the burden on the container
  14212. * generator to house the arcane code for determining these for current & future formats.
  14213. *
  14214. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14215. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14216. *
  14217. * Note: The result of this call is not taken into account when a texture is base64.
  14218. *
  14219. * @param formatsAvailable defines the list of those format families you have created
  14220. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14221. *
  14222. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14223. * @returns The extension selected.
  14224. */
  14225. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14226. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14227. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14228. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14229. return this._textureFormatInUse = this._texturesSupported[i];
  14230. }
  14231. }
  14232. }
  14233. // actively set format to nothing, to allow this to be called more than once
  14234. // and possibly fail the 2nd time
  14235. this._textureFormatInUse = null;
  14236. return null;
  14237. };
  14238. /** @ignore */
  14239. Engine.prototype._createTexture = function () {
  14240. var texture = this._gl.createTexture();
  14241. if (!texture) {
  14242. throw new Error("Unable to create texture");
  14243. }
  14244. return texture;
  14245. };
  14246. /**
  14247. * Usually called from BABYLON.Texture.ts.
  14248. * Passed information to create a WebGLTexture
  14249. * @param urlArg defines a value which contains one of the following:
  14250. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14251. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14252. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14253. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14254. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14255. * @param scene needed for loading to the correct scene
  14256. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14257. * @param onLoad optional callback to be called upon successful completion
  14258. * @param onError optional callback to be called upon failure
  14259. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14260. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14261. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14262. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14263. */
  14264. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14265. var _this = this;
  14266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14267. if (onLoad === void 0) { onLoad = null; }
  14268. if (onError === void 0) { onError = null; }
  14269. if (buffer === void 0) { buffer = null; }
  14270. if (fallback === void 0) { fallback = null; }
  14271. if (format === void 0) { format = null; }
  14272. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14273. var fromData = url.substr(0, 5) === "data:";
  14274. var fromBlob = url.substr(0, 5) === "blob:";
  14275. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14276. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14277. // establish the file extension, if possible
  14278. var lastDot = url.lastIndexOf('.');
  14279. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14280. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14281. var isTGA = (extension.indexOf(".tga") === 0);
  14282. // determine if a ktx file should be substituted
  14283. var isKTX = false;
  14284. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14285. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14286. isKTX = true;
  14287. }
  14288. if (scene) {
  14289. scene._addPendingData(texture);
  14290. }
  14291. texture.url = url;
  14292. texture.generateMipMaps = !noMipmap;
  14293. texture.samplingMode = samplingMode;
  14294. texture.invertY = invertY;
  14295. if (!this._doNotHandleContextLost) {
  14296. // Keep a link to the buffer only if we plan to handle context lost
  14297. texture._buffer = buffer;
  14298. }
  14299. var onLoadObserver = null;
  14300. if (onLoad && !fallback) {
  14301. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14302. }
  14303. if (!fallback)
  14304. this._internalTexturesCache.push(texture);
  14305. var onerror = function (message, exception) {
  14306. if (scene) {
  14307. scene._removePendingData(texture);
  14308. }
  14309. if (onLoadObserver) {
  14310. texture.onLoadedObservable.remove(onLoadObserver);
  14311. }
  14312. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14313. if (isKTX) {
  14314. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14315. }
  14316. else if (BABYLON.Tools.UseFallbackTexture) {
  14317. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14318. }
  14319. if (onError) {
  14320. onError(message || "Unknown error", exception);
  14321. }
  14322. };
  14323. var callback = null;
  14324. // processing for non-image formats
  14325. if (isKTX || isTGA || isDDS) {
  14326. if (isKTX) {
  14327. callback = function (data) {
  14328. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14329. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14330. ktx.uploadLevels(_this._gl, !noMipmap);
  14331. return false;
  14332. }, samplingMode);
  14333. };
  14334. }
  14335. else if (isTGA) {
  14336. callback = function (arrayBuffer) {
  14337. var data = new Uint8Array(arrayBuffer);
  14338. var header = BABYLON.TGATools.GetTGAHeader(data);
  14339. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14340. BABYLON.TGATools.UploadContent(_this._gl, data);
  14341. return false;
  14342. }, samplingMode);
  14343. };
  14344. }
  14345. else if (isDDS) {
  14346. callback = function (data) {
  14347. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14348. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14349. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14350. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14351. return false;
  14352. }, samplingMode);
  14353. };
  14354. }
  14355. if (!buffer) {
  14356. this._loadFile(url, function (data) {
  14357. if (callback) {
  14358. callback(data);
  14359. }
  14360. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14361. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14362. });
  14363. }
  14364. else {
  14365. if (callback) {
  14366. callback(buffer);
  14367. }
  14368. }
  14369. // image format processing
  14370. }
  14371. else {
  14372. var onload = function (img) {
  14373. if (fromBlob && !_this._doNotHandleContextLost) {
  14374. // We need to store the image if we need to rebuild the texture
  14375. // in case of a webgl context lost
  14376. texture._buffer = img;
  14377. }
  14378. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14379. var gl = _this._gl;
  14380. var isPot = (img.width === potWidth && img.height === potHeight);
  14381. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14382. if (isPot) {
  14383. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14384. return false;
  14385. }
  14386. // Using shaders to rescale because canvas.drawImage is lossy
  14387. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14388. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14389. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14394. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14395. _this._releaseTexture(source);
  14396. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14397. continuationCallback();
  14398. });
  14399. return true;
  14400. }, samplingMode);
  14401. };
  14402. if (!fromData || isBase64)
  14403. if (buffer instanceof HTMLImageElement) {
  14404. onload(buffer);
  14405. }
  14406. else {
  14407. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14408. }
  14409. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14410. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14411. else
  14412. onload(buffer);
  14413. }
  14414. return texture;
  14415. };
  14416. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14417. var _this = this;
  14418. var rtt = this.createRenderTargetTexture({
  14419. width: destination.width,
  14420. height: destination.height,
  14421. }, {
  14422. generateMipMaps: false,
  14423. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14424. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14425. generateDepthBuffer: false,
  14426. generateStencilBuffer: false
  14427. });
  14428. if (!this._rescalePostProcess) {
  14429. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14430. }
  14431. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14432. _this._rescalePostProcess.onApply = function (effect) {
  14433. effect._bindTexture("textureSampler", source);
  14434. };
  14435. var hostingScene = scene;
  14436. if (!hostingScene) {
  14437. hostingScene = _this.scenes[_this.scenes.length - 1];
  14438. }
  14439. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14440. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14441. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14442. _this.unBindFramebuffer(rtt);
  14443. _this._releaseTexture(rtt);
  14444. if (onComplete) {
  14445. onComplete();
  14446. }
  14447. });
  14448. };
  14449. /**
  14450. * Update a raw texture
  14451. * @param texture defines the texture to update
  14452. * @param data defines the data to store in the texture
  14453. * @param format defines the format of the data
  14454. * @param invertY defines if data must be stored with Y axis inverted
  14455. * @param compression defines the compression used (null by default)
  14456. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14457. */
  14458. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14459. if (compression === void 0) { compression = null; }
  14460. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14461. if (!texture) {
  14462. return;
  14463. }
  14464. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14465. var internalFormat = this._getInternalFormat(format);
  14466. var textureType = this._getWebGLTextureType(type);
  14467. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14468. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14469. if (!this._doNotHandleContextLost) {
  14470. texture._bufferView = data;
  14471. texture.format = format;
  14472. texture.type = type;
  14473. texture.invertY = invertY;
  14474. texture._compression = compression;
  14475. }
  14476. if (texture.width % 4 !== 0) {
  14477. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14478. }
  14479. if (compression && data) {
  14480. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14481. }
  14482. else {
  14483. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14484. }
  14485. if (texture.generateMipMaps) {
  14486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14487. }
  14488. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14489. // this.resetTextureCache();
  14490. texture.isReady = true;
  14491. };
  14492. /**
  14493. * Creates a raw texture
  14494. * @param data defines the data to store in the texture
  14495. * @param width defines the width of the texture
  14496. * @param height defines the height of the texture
  14497. * @param format defines the format of the data
  14498. * @param generateMipMaps defines if the engine should generate the mip levels
  14499. * @param invertY defines if data must be stored with Y axis inverted
  14500. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14501. * @param compression defines the compression used (null by default)
  14502. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14503. * @returns the raw texture inside an InternalTexture
  14504. */
  14505. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14506. if (compression === void 0) { compression = null; }
  14507. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14509. texture.baseWidth = width;
  14510. texture.baseHeight = height;
  14511. texture.width = width;
  14512. texture.height = height;
  14513. texture.format = format;
  14514. texture.generateMipMaps = generateMipMaps;
  14515. texture.samplingMode = samplingMode;
  14516. texture.invertY = invertY;
  14517. texture._compression = compression;
  14518. texture.type = type;
  14519. if (!this._doNotHandleContextLost) {
  14520. texture._bufferView = data;
  14521. }
  14522. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14523. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14524. // Filters
  14525. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14528. if (generateMipMaps) {
  14529. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14530. }
  14531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14532. this._internalTexturesCache.push(texture);
  14533. return texture;
  14534. };
  14535. /**
  14536. * Creates a dynamic texture
  14537. * @param width defines the width of the texture
  14538. * @param height defines the height of the texture
  14539. * @param generateMipMaps defines if the engine should generate the mip levels
  14540. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14541. * @returns the dynamic texture inside an InternalTexture
  14542. */
  14543. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14544. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14545. texture.baseWidth = width;
  14546. texture.baseHeight = height;
  14547. if (generateMipMaps) {
  14548. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14549. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14550. }
  14551. // this.resetTextureCache();
  14552. texture.width = width;
  14553. texture.height = height;
  14554. texture.isReady = false;
  14555. texture.generateMipMaps = generateMipMaps;
  14556. texture.samplingMode = samplingMode;
  14557. this.updateTextureSamplingMode(samplingMode, texture);
  14558. this._internalTexturesCache.push(texture);
  14559. return texture;
  14560. };
  14561. /**
  14562. * Update the sampling mode of a given texture
  14563. * @param samplingMode defines the required sampling mode
  14564. * @param texture defines the texture to update
  14565. */
  14566. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14567. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14568. if (texture.isCube) {
  14569. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14570. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14571. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14572. }
  14573. else if (texture.is3D) {
  14574. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14575. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14576. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14577. }
  14578. else {
  14579. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14580. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14581. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14582. }
  14583. texture.samplingMode = samplingMode;
  14584. };
  14585. /**
  14586. * Update the content of a dynamic texture
  14587. * @param texture defines the texture to update
  14588. * @param canvas defines the canvas containing the source
  14589. * @param invertY defines if data must be stored with Y axis inverted
  14590. * @param premulAlpha defines if alpha is stored as premultiplied
  14591. * @param format defines the format of the data
  14592. */
  14593. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14594. if (premulAlpha === void 0) { premulAlpha = false; }
  14595. if (!texture) {
  14596. return;
  14597. }
  14598. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14599. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14600. if (premulAlpha) {
  14601. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14602. }
  14603. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14604. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14605. if (texture.generateMipMaps) {
  14606. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14607. }
  14608. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14609. if (premulAlpha) {
  14610. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14611. }
  14612. texture.isReady = true;
  14613. };
  14614. /**
  14615. * Update a video texture
  14616. * @param texture defines the texture to update
  14617. * @param video defines the video element to use
  14618. * @param invertY defines if data must be stored with Y axis inverted
  14619. */
  14620. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14621. if (!texture || texture._isDisabled) {
  14622. return;
  14623. }
  14624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14625. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14626. try {
  14627. // Testing video texture support
  14628. if (this._videoTextureSupported === undefined) {
  14629. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14630. if (this._gl.getError() !== 0) {
  14631. this._videoTextureSupported = false;
  14632. }
  14633. else {
  14634. this._videoTextureSupported = true;
  14635. }
  14636. }
  14637. // Copy video through the current working canvas if video texture is not supported
  14638. if (!this._videoTextureSupported) {
  14639. if (!texture._workingCanvas) {
  14640. texture._workingCanvas = document.createElement("canvas");
  14641. var context = texture._workingCanvas.getContext("2d");
  14642. if (!context) {
  14643. throw new Error("Unable to get 2d context");
  14644. }
  14645. texture._workingContext = context;
  14646. texture._workingCanvas.width = texture.width;
  14647. texture._workingCanvas.height = texture.height;
  14648. }
  14649. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14650. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. }
  14662. catch (ex) {
  14663. // Something unexpected
  14664. // Let's disable the texture
  14665. texture._isDisabled = true;
  14666. }
  14667. };
  14668. /**
  14669. * Updates a depth texture Comparison Mode and Function.
  14670. * If the comparison Function is equal to 0, the mode will be set to none.
  14671. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14672. * @param texture The texture to set the comparison function for
  14673. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14674. */
  14675. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14676. if (this.webGLVersion === 1) {
  14677. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14678. return;
  14679. }
  14680. var gl = this._gl;
  14681. if (texture.isCube) {
  14682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14683. if (comparisonFunction === 0) {
  14684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14686. }
  14687. else {
  14688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14692. }
  14693. else {
  14694. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14695. if (comparisonFunction === 0) {
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14698. }
  14699. else {
  14700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14701. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14702. }
  14703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14704. }
  14705. texture._comparisonFunction = comparisonFunction;
  14706. };
  14707. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14708. var width = size.width || size;
  14709. var height = size.height || size;
  14710. internalTexture.baseWidth = width;
  14711. internalTexture.baseHeight = height;
  14712. internalTexture.width = width;
  14713. internalTexture.height = height;
  14714. internalTexture.isReady = true;
  14715. internalTexture.samples = 1;
  14716. internalTexture.generateMipMaps = false;
  14717. internalTexture._generateDepthBuffer = true;
  14718. internalTexture._generateStencilBuffer = generateStencil;
  14719. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14720. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14721. internalTexture._comparisonFunction = comparisonFunction;
  14722. var gl = this._gl;
  14723. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14724. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14725. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14726. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14727. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14728. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14729. if (comparisonFunction === 0) {
  14730. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14731. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14732. }
  14733. else {
  14734. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14735. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14736. }
  14737. };
  14738. /**
  14739. * Creates a depth stencil texture.
  14740. * This is only available in WebGL 2 or with the depth texture extension available.
  14741. * @param size The size of face edge in the texture.
  14742. * @param options The options defining the texture.
  14743. * @returns The texture
  14744. */
  14745. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14746. if (options.isCube) {
  14747. var width = size.width || size;
  14748. return this._createDepthStencilCubeTexture(width, options);
  14749. }
  14750. else {
  14751. return this._createDepthStencilTexture(size, options);
  14752. }
  14753. };
  14754. /**
  14755. * Creates a depth stencil texture.
  14756. * This is only available in WebGL 2 or with the depth texture extension available.
  14757. * @param size The size of face edge in the texture.
  14758. * @param options The options defining the texture.
  14759. * @returns The texture
  14760. */
  14761. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14762. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14763. if (!this._caps.depthTextureExtension) {
  14764. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14765. return internalTexture;
  14766. }
  14767. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14768. var gl = this._gl;
  14769. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14770. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14771. if (this.webGLVersion > 1) {
  14772. if (internalOptions.generateStencil) {
  14773. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14774. }
  14775. else {
  14776. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14777. }
  14778. }
  14779. else {
  14780. if (internalOptions.generateStencil) {
  14781. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14782. }
  14783. else {
  14784. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14785. }
  14786. }
  14787. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14788. return internalTexture;
  14789. };
  14790. /**
  14791. * Creates a depth stencil cube texture.
  14792. * This is only available in WebGL 2.
  14793. * @param size The size of face edge in the cube texture.
  14794. * @param options The options defining the cube texture.
  14795. * @returns The cube texture
  14796. */
  14797. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14798. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14799. internalTexture.isCube = true;
  14800. if (this.webGLVersion === 1) {
  14801. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14802. return internalTexture;
  14803. }
  14804. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14805. var gl = this._gl;
  14806. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14807. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14808. // Create the depth/stencil buffer
  14809. for (var face = 0; face < 6; face++) {
  14810. if (internalOptions.generateStencil) {
  14811. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14812. }
  14813. else {
  14814. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14815. }
  14816. }
  14817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14818. return internalTexture;
  14819. };
  14820. /**
  14821. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14822. * @param renderTarget The render target to set the frame buffer for
  14823. */
  14824. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14825. // Create the framebuffer
  14826. var internalTexture = renderTarget.getInternalTexture();
  14827. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14828. return;
  14829. }
  14830. var gl = this._gl;
  14831. var depthStencilTexture = renderTarget.depthStencilTexture;
  14832. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14833. if (depthStencilTexture.isCube) {
  14834. if (depthStencilTexture._generateStencilBuffer) {
  14835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14836. }
  14837. else {
  14838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14839. }
  14840. }
  14841. else {
  14842. if (depthStencilTexture._generateStencilBuffer) {
  14843. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14844. }
  14845. else {
  14846. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14847. }
  14848. }
  14849. this.bindUnboundFramebuffer(null);
  14850. };
  14851. /**
  14852. * Creates a new render target texture
  14853. * @param size defines the size of the texture
  14854. * @param options defines the options used to create the texture
  14855. * @returns a new render target texture stored in an InternalTexture
  14856. */
  14857. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14858. var fullOptions = new RenderTargetCreationOptions();
  14859. if (options !== undefined && typeof options === "object") {
  14860. fullOptions.generateMipMaps = options.generateMipMaps;
  14861. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14862. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14863. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14864. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14865. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14866. }
  14867. else {
  14868. fullOptions.generateMipMaps = options;
  14869. fullOptions.generateDepthBuffer = true;
  14870. fullOptions.generateStencilBuffer = false;
  14871. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14872. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14873. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14874. }
  14875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14878. }
  14879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14882. }
  14883. var gl = this._gl;
  14884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14885. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14886. var width = size.width || size;
  14887. var height = size.height || size;
  14888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14892. }
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14898. // Create the framebuffer
  14899. var framebuffer = gl.createFramebuffer();
  14900. this.bindUnboundFramebuffer(framebuffer);
  14901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14903. if (fullOptions.generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. // Unbind
  14907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14909. this.bindUnboundFramebuffer(null);
  14910. texture._framebuffer = framebuffer;
  14911. texture.baseWidth = width;
  14912. texture.baseHeight = height;
  14913. texture.width = width;
  14914. texture.height = height;
  14915. texture.isReady = true;
  14916. texture.samples = 1;
  14917. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14918. texture.samplingMode = fullOptions.samplingMode;
  14919. texture.type = fullOptions.type;
  14920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14922. // this.resetTextureCache();
  14923. this._internalTexturesCache.push(texture);
  14924. return texture;
  14925. };
  14926. /**
  14927. * Create a multi render target texture
  14928. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14929. * @param size defines the size of the texture
  14930. * @param options defines the creation options
  14931. * @returns the cube texture as an InternalTexture
  14932. */
  14933. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14934. var generateMipMaps = false;
  14935. var generateDepthBuffer = true;
  14936. var generateStencilBuffer = false;
  14937. var generateDepthTexture = false;
  14938. var textureCount = 1;
  14939. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14940. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14941. var types = new Array();
  14942. var samplingModes = new Array();
  14943. if (options !== undefined) {
  14944. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14945. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14946. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14947. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14948. textureCount = options.textureCount || 1;
  14949. if (options.types) {
  14950. types = options.types;
  14951. }
  14952. if (options.samplingModes) {
  14953. samplingModes = options.samplingModes;
  14954. }
  14955. }
  14956. var gl = this._gl;
  14957. // Create the framebuffer
  14958. var framebuffer = gl.createFramebuffer();
  14959. this.bindUnboundFramebuffer(framebuffer);
  14960. var width = size.width || size;
  14961. var height = size.height || size;
  14962. var textures = [];
  14963. var attachments = [];
  14964. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14965. for (var i = 0; i < textureCount; i++) {
  14966. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14967. var type = types[i] || defaultType;
  14968. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14969. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14970. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14971. }
  14972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14973. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14974. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14975. }
  14976. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14977. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14978. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14979. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14980. }
  14981. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14982. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14983. textures.push(texture);
  14984. attachments.push(attachment);
  14985. gl.activeTexture(gl["TEXTURE" + i]);
  14986. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14991. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14992. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14993. if (generateMipMaps) {
  14994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14995. }
  14996. // Unbind
  14997. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14998. texture._framebuffer = framebuffer;
  14999. texture._depthStencilBuffer = depthStencilBuffer;
  15000. texture.baseWidth = width;
  15001. texture.baseHeight = height;
  15002. texture.width = width;
  15003. texture.height = height;
  15004. texture.isReady = true;
  15005. texture.samples = 1;
  15006. texture.generateMipMaps = generateMipMaps;
  15007. texture.samplingMode = samplingMode;
  15008. texture.type = type;
  15009. texture._generateDepthBuffer = generateDepthBuffer;
  15010. texture._generateStencilBuffer = generateStencilBuffer;
  15011. texture._attachments = attachments;
  15012. this._internalTexturesCache.push(texture);
  15013. }
  15014. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15015. // Depth texture
  15016. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15017. gl.activeTexture(gl.TEXTURE0);
  15018. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15023. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15025. depthTexture._framebuffer = framebuffer;
  15026. depthTexture.baseWidth = width;
  15027. depthTexture.baseHeight = height;
  15028. depthTexture.width = width;
  15029. depthTexture.height = height;
  15030. depthTexture.isReady = true;
  15031. depthTexture.samples = 1;
  15032. depthTexture.generateMipMaps = generateMipMaps;
  15033. depthTexture.samplingMode = gl.NEAREST;
  15034. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15035. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15036. textures.push(depthTexture);
  15037. this._internalTexturesCache.push(depthTexture);
  15038. }
  15039. gl.drawBuffers(attachments);
  15040. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15041. this.bindUnboundFramebuffer(null);
  15042. this.resetTextureCache();
  15043. return textures;
  15044. };
  15045. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15046. if (samples === void 0) { samples = 1; }
  15047. var depthStencilBuffer = null;
  15048. var gl = this._gl;
  15049. // Create the depth/stencil buffer
  15050. if (generateStencilBuffer) {
  15051. depthStencilBuffer = gl.createRenderbuffer();
  15052. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15053. if (samples > 1) {
  15054. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15055. }
  15056. else {
  15057. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15058. }
  15059. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15060. }
  15061. else if (generateDepthBuffer) {
  15062. depthStencilBuffer = gl.createRenderbuffer();
  15063. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15064. if (samples > 1) {
  15065. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15066. }
  15067. else {
  15068. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15069. }
  15070. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15071. }
  15072. return depthStencilBuffer;
  15073. };
  15074. /**
  15075. * Updates the sample count of a render target texture
  15076. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15077. * @param texture defines the texture to update
  15078. * @param samples defines the sample count to set
  15079. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15080. */
  15081. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15082. if (this.webGLVersion < 2 || !texture) {
  15083. return 1;
  15084. }
  15085. if (texture.samples === samples) {
  15086. return samples;
  15087. }
  15088. var gl = this._gl;
  15089. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15090. // Dispose previous render buffers
  15091. if (texture._depthStencilBuffer) {
  15092. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15093. texture._depthStencilBuffer = null;
  15094. }
  15095. if (texture._MSAAFramebuffer) {
  15096. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15097. texture._MSAAFramebuffer = null;
  15098. }
  15099. if (texture._MSAARenderBuffer) {
  15100. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15101. texture._MSAARenderBuffer = null;
  15102. }
  15103. if (samples > 1) {
  15104. var framebuffer = gl.createFramebuffer();
  15105. if (!framebuffer) {
  15106. throw new Error("Unable to create multi sampled framebuffer");
  15107. }
  15108. texture._MSAAFramebuffer = framebuffer;
  15109. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15110. var colorRenderbuffer = gl.createRenderbuffer();
  15111. if (!colorRenderbuffer) {
  15112. throw new Error("Unable to create multi sampled framebuffer");
  15113. }
  15114. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15115. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15116. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15117. texture._MSAARenderBuffer = colorRenderbuffer;
  15118. }
  15119. else {
  15120. this.bindUnboundFramebuffer(texture._framebuffer);
  15121. }
  15122. texture.samples = samples;
  15123. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15124. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15125. this.bindUnboundFramebuffer(null);
  15126. return samples;
  15127. };
  15128. /**
  15129. * Update the sample count for a given multiple render target texture
  15130. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15131. * @param textures defines the textures to update
  15132. * @param samples defines the sample count to set
  15133. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15134. */
  15135. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15136. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15137. return 1;
  15138. }
  15139. if (textures[0].samples === samples) {
  15140. return samples;
  15141. }
  15142. var gl = this._gl;
  15143. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15144. // Dispose previous render buffers
  15145. if (textures[0]._depthStencilBuffer) {
  15146. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15147. textures[0]._depthStencilBuffer = null;
  15148. }
  15149. if (textures[0]._MSAAFramebuffer) {
  15150. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15151. textures[0]._MSAAFramebuffer = null;
  15152. }
  15153. for (var i = 0; i < textures.length; i++) {
  15154. if (textures[i]._MSAARenderBuffer) {
  15155. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15156. textures[i]._MSAARenderBuffer = null;
  15157. }
  15158. }
  15159. if (samples > 1) {
  15160. var framebuffer = gl.createFramebuffer();
  15161. if (!framebuffer) {
  15162. throw new Error("Unable to create multi sampled framebuffer");
  15163. }
  15164. this.bindUnboundFramebuffer(framebuffer);
  15165. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15166. var attachments = [];
  15167. for (var i = 0; i < textures.length; i++) {
  15168. var texture = textures[i];
  15169. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15170. var colorRenderbuffer = gl.createRenderbuffer();
  15171. if (!colorRenderbuffer) {
  15172. throw new Error("Unable to create multi sampled framebuffer");
  15173. }
  15174. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15175. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15176. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15177. texture._MSAAFramebuffer = framebuffer;
  15178. texture._MSAARenderBuffer = colorRenderbuffer;
  15179. texture.samples = samples;
  15180. texture._depthStencilBuffer = depthStencilBuffer;
  15181. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15182. attachments.push(attachment);
  15183. }
  15184. gl.drawBuffers(attachments);
  15185. }
  15186. else {
  15187. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15188. }
  15189. this.bindUnboundFramebuffer(null);
  15190. return samples;
  15191. };
  15192. /** @ignore */
  15193. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15194. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15195. };
  15196. /** @ignore */
  15197. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15198. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15199. };
  15200. /**
  15201. * Creates a new render target cube texture
  15202. * @param size defines the size of the texture
  15203. * @param options defines the options used to create the texture
  15204. * @returns a new render target cube texture stored in an InternalTexture
  15205. */
  15206. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15207. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15208. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15209. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15210. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15211. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15212. }
  15213. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15214. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15215. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15216. }
  15217. var gl = this._gl;
  15218. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15219. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15220. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15221. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15222. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15223. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15224. }
  15225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15229. for (var face = 0; face < 6; face++) {
  15230. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15231. }
  15232. // Create the framebuffer
  15233. var framebuffer = gl.createFramebuffer();
  15234. this.bindUnboundFramebuffer(framebuffer);
  15235. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15236. // MipMaps
  15237. if (fullOptions.generateMipMaps) {
  15238. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15239. }
  15240. // Unbind
  15241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15242. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15243. this.bindUnboundFramebuffer(null);
  15244. texture._framebuffer = framebuffer;
  15245. texture.width = size;
  15246. texture.height = size;
  15247. texture.isReady = true;
  15248. texture.isCube = true;
  15249. texture.samples = 1;
  15250. texture.generateMipMaps = fullOptions.generateMipMaps;
  15251. texture.samplingMode = fullOptions.samplingMode;
  15252. texture.type = fullOptions.type;
  15253. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15254. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15255. this._internalTexturesCache.push(texture);
  15256. return texture;
  15257. };
  15258. /**
  15259. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15260. * @param rootUrl defines the url where the file to load is located
  15261. * @param scene defines the current scene
  15262. * @param scale defines scale to apply to the mip map selection
  15263. * @param offset defines offset to apply to the mip map selection
  15264. * @param onLoad defines an optional callback raised when the texture is loaded
  15265. * @param onError defines an optional callback raised if there is an issue to load the texture
  15266. * @param format defines the format of the data
  15267. * @param forcedExtension defines the extension to use to pick the right loader
  15268. * @returns the cube texture as an InternalTexture
  15269. */
  15270. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15271. var _this = this;
  15272. if (onLoad === void 0) { onLoad = null; }
  15273. if (onError === void 0) { onError = null; }
  15274. if (forcedExtension === void 0) { forcedExtension = null; }
  15275. var callback = function (loadData) {
  15276. if (!loadData) {
  15277. if (onLoad) {
  15278. onLoad(null);
  15279. }
  15280. return;
  15281. }
  15282. var texture = loadData.texture;
  15283. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15284. texture._lodGenerationScale = scale;
  15285. texture._lodGenerationOffset = offset;
  15286. if (_this._caps.textureLOD) {
  15287. // Do not add extra process if texture lod is supported.
  15288. if (onLoad) {
  15289. onLoad(texture);
  15290. }
  15291. return;
  15292. }
  15293. var mipSlices = 3;
  15294. var gl = _this._gl;
  15295. var width = loadData.width;
  15296. if (!width) {
  15297. return;
  15298. }
  15299. var textures = [];
  15300. for (var i = 0; i < mipSlices; i++) {
  15301. //compute LOD from even spacing in smoothness (matching shader calculation)
  15302. var smoothness = i / (mipSlices - 1);
  15303. var roughness = 1 - smoothness;
  15304. var minLODIndex = offset; // roughness = 0
  15305. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15306. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15307. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15308. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15309. glTextureFromLod.isCube = true;
  15310. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15315. if (loadData.isDDS) {
  15316. var info = loadData.info;
  15317. var data = loadData.data;
  15318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15319. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15320. }
  15321. else {
  15322. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15323. }
  15324. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15325. // Wrap in a base texture for easy binding.
  15326. var lodTexture = new BABYLON.BaseTexture(scene);
  15327. lodTexture.isCube = true;
  15328. lodTexture._texture = glTextureFromLod;
  15329. glTextureFromLod.isReady = true;
  15330. textures.push(lodTexture);
  15331. }
  15332. texture._lodTextureHigh = textures[2];
  15333. texture._lodTextureMid = textures[1];
  15334. texture._lodTextureLow = textures[0];
  15335. if (onLoad) {
  15336. onLoad(texture);
  15337. }
  15338. };
  15339. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15340. };
  15341. /**
  15342. * Creates a cube texture
  15343. * @param rootUrl defines the url where the files to load is located
  15344. * @param scene defines the current scene
  15345. * @param files defines the list of files to load (1 per face)
  15346. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15347. * @param onLoad defines an optional callback raised when the texture is loaded
  15348. * @param onError defines an optional callback raised if there is an issue to load the texture
  15349. * @param format defines the format of the data
  15350. * @param forcedExtension defines the extension to use to pick the right loader
  15351. * @returns the cube texture as an InternalTexture
  15352. */
  15353. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15354. var _this = this;
  15355. if (onLoad === void 0) { onLoad = null; }
  15356. if (onError === void 0) { onError = null; }
  15357. if (forcedExtension === void 0) { forcedExtension = null; }
  15358. var gl = this._gl;
  15359. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15360. texture.isCube = true;
  15361. texture.url = rootUrl;
  15362. texture.generateMipMaps = !noMipmap;
  15363. if (!this._doNotHandleContextLost) {
  15364. texture._extension = forcedExtension;
  15365. texture._files = files;
  15366. }
  15367. var isKTX = false;
  15368. var isDDS = false;
  15369. var lastDot = rootUrl.lastIndexOf('.');
  15370. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15371. if (this._textureFormatInUse) {
  15372. extension = this._textureFormatInUse;
  15373. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15374. isKTX = true;
  15375. }
  15376. else {
  15377. isDDS = (extension === ".dds");
  15378. }
  15379. var onerror = function (request, exception) {
  15380. if (onError && request) {
  15381. onError(request.status + " " + request.statusText, exception);
  15382. }
  15383. };
  15384. if (isKTX) {
  15385. this._loadFile(rootUrl, function (data) {
  15386. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15387. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15388. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15389. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15390. ktx.uploadLevels(_this._gl, !noMipmap);
  15391. _this.setCubeMapTextureParams(gl, loadMipmap);
  15392. texture.width = ktx.pixelWidth;
  15393. texture.height = ktx.pixelHeight;
  15394. texture.isReady = true;
  15395. }, undefined, undefined, true, onerror);
  15396. }
  15397. else if (isDDS) {
  15398. if (files && files.length === 6) {
  15399. this._cascadeLoadFiles(scene, function (imgs) {
  15400. var info;
  15401. var loadMipmap = false;
  15402. var width = 0;
  15403. for (var index = 0; index < imgs.length; index++) {
  15404. var data = imgs[index];
  15405. info = BABYLON.DDSTools.GetDDSInfo(data);
  15406. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15409. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15410. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15411. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15412. }
  15413. texture.width = info.width;
  15414. texture.height = info.height;
  15415. texture.type = info.textureType;
  15416. width = info.width;
  15417. }
  15418. _this.setCubeMapTextureParams(gl, loadMipmap);
  15419. texture.isReady = true;
  15420. if (onLoad) {
  15421. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15422. }
  15423. }, files, onError);
  15424. }
  15425. else {
  15426. this._loadFile(rootUrl, function (data) {
  15427. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15428. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15429. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15430. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15431. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15432. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15433. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15434. }
  15435. _this.setCubeMapTextureParams(gl, loadMipmap);
  15436. texture.width = info.width;
  15437. texture.height = info.height;
  15438. texture.isReady = true;
  15439. texture.type = info.textureType;
  15440. if (onLoad) {
  15441. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15442. }
  15443. }, undefined, undefined, true, onerror);
  15444. }
  15445. }
  15446. else {
  15447. if (!files) {
  15448. throw new Error("Cannot load cubemap because files were not defined");
  15449. }
  15450. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15451. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15452. var height = width;
  15453. _this._prepareWorkingCanvas();
  15454. if (!_this._workingCanvas || !_this._workingContext) {
  15455. return;
  15456. }
  15457. _this._workingCanvas.width = width;
  15458. _this._workingCanvas.height = height;
  15459. var faces = [
  15460. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15461. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15462. ];
  15463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15464. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15465. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15466. for (var index = 0; index < faces.length; index++) {
  15467. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15468. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15469. }
  15470. if (!noMipmap) {
  15471. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15472. }
  15473. _this.setCubeMapTextureParams(gl, !noMipmap);
  15474. texture.width = width;
  15475. texture.height = height;
  15476. texture.isReady = true;
  15477. if (format) {
  15478. texture.format = format;
  15479. }
  15480. texture.onLoadedObservable.notifyObservers(texture);
  15481. texture.onLoadedObservable.clear();
  15482. if (onLoad) {
  15483. onLoad();
  15484. }
  15485. }, files, onError);
  15486. }
  15487. this._internalTexturesCache.push(texture);
  15488. return texture;
  15489. };
  15490. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15495. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15496. // this.resetTextureCache();
  15497. };
  15498. /**
  15499. * Update a raw cube texture
  15500. * @param texture defines the texture to udpdate
  15501. * @param data defines the data to store
  15502. * @param format defines the data format
  15503. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15504. * @param invertY defines if data must be stored with Y axis inverted
  15505. * @param compression defines the compression used (null by default)
  15506. * @param level defines which level of the texture to update
  15507. */
  15508. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15509. if (compression === void 0) { compression = null; }
  15510. if (level === void 0) { level = 0; }
  15511. texture._bufferViewArray = data;
  15512. texture.format = format;
  15513. texture.type = type;
  15514. texture.invertY = invertY;
  15515. texture._compression = compression;
  15516. var gl = this._gl;
  15517. var textureType = this._getWebGLTextureType(type);
  15518. var internalFormat = this._getInternalFormat(format);
  15519. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15520. var needConversion = false;
  15521. if (internalFormat === gl.RGB) {
  15522. internalFormat = gl.RGBA;
  15523. needConversion = true;
  15524. }
  15525. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15527. if (texture.width % 4 !== 0) {
  15528. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15529. }
  15530. // Data are known to be in +X +Y +Z -X -Y -Z
  15531. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15532. var faceData = data[faceIndex];
  15533. if (compression) {
  15534. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15535. }
  15536. else {
  15537. if (needConversion) {
  15538. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15539. }
  15540. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15541. }
  15542. }
  15543. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15544. if (isPot && texture.generateMipMaps && level === 0) {
  15545. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15546. }
  15547. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15548. // this.resetTextureCache();
  15549. texture.isReady = true;
  15550. };
  15551. /**
  15552. * Creates a new raw cube texture
  15553. * @param data defines the array of data to use to create each face
  15554. * @param size defines the size of the textures
  15555. * @param format defines the format of the data
  15556. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15557. * @param generateMipMaps defines if the engine should generate the mip levels
  15558. * @param invertY defines if data must be stored with Y axis inverted
  15559. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15560. * @param compression defines the compression used (null by default)
  15561. * @returns the cube texture as an InternalTexture
  15562. */
  15563. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15564. if (compression === void 0) { compression = null; }
  15565. var gl = this._gl;
  15566. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15567. texture.isCube = true;
  15568. texture.generateMipMaps = generateMipMaps;
  15569. texture.format = format;
  15570. texture.type = type;
  15571. if (!this._doNotHandleContextLost) {
  15572. texture._bufferViewArray = data;
  15573. }
  15574. var textureType = this._getWebGLTextureType(type);
  15575. var internalFormat = this._getInternalFormat(format);
  15576. if (internalFormat === gl.RGB) {
  15577. internalFormat = gl.RGBA;
  15578. }
  15579. var width = size;
  15580. var height = width;
  15581. texture.width = width;
  15582. texture.height = height;
  15583. // Double check on POT to generate Mips.
  15584. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15585. if (!isPot) {
  15586. generateMipMaps = false;
  15587. }
  15588. // Upload data if needed. The texture won't be ready until then.
  15589. if (data) {
  15590. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15591. }
  15592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15593. // Filters
  15594. if (data && generateMipMaps) {
  15595. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15596. }
  15597. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15600. }
  15601. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15604. }
  15605. else {
  15606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15609. }
  15610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15613. return texture;
  15614. };
  15615. /**
  15616. * Creates a new raw cube texture from a specified url
  15617. * @param url defines the url where the data is located
  15618. * @param scene defines the current scene
  15619. * @param size defines the size of the textures
  15620. * @param format defines the format of the data
  15621. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15622. * @param noMipmap defines if the engine should avoid generating the mip levels
  15623. * @param callback defines a callback used to extract texture data from loaded data
  15624. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15625. * @param onLoad defines a callback called when texture is loaded
  15626. * @param onError defines a callback called if there is an error
  15627. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15628. * @param invertY defines if data must be stored with Y axis inverted
  15629. * @returns the cube texture as an InternalTexture
  15630. */
  15631. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15632. var _this = this;
  15633. if (onLoad === void 0) { onLoad = null; }
  15634. if (onError === void 0) { onError = null; }
  15635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15636. if (invertY === void 0) { invertY = false; }
  15637. var gl = this._gl;
  15638. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15639. scene._addPendingData(texture);
  15640. texture.url = url;
  15641. this._internalTexturesCache.push(texture);
  15642. var onerror = function (request, exception) {
  15643. scene._removePendingData(texture);
  15644. if (onError && request) {
  15645. onError(request.status + " " + request.statusText, exception);
  15646. }
  15647. };
  15648. var internalCallback = function (data) {
  15649. var width = texture.width;
  15650. var faceDataArrays = callback(data);
  15651. if (!faceDataArrays) {
  15652. return;
  15653. }
  15654. if (mipmapGenerator) {
  15655. var textureType = _this._getWebGLTextureType(type);
  15656. var internalFormat = _this._getInternalFormat(format);
  15657. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15658. var needConversion = false;
  15659. if (internalFormat === gl.RGB) {
  15660. internalFormat = gl.RGBA;
  15661. needConversion = true;
  15662. }
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15665. var mipData = mipmapGenerator(faceDataArrays);
  15666. for (var level = 0; level < mipData.length; level++) {
  15667. var mipSize = width >> level;
  15668. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15669. var mipFaceData = mipData[level][faceIndex];
  15670. if (needConversion) {
  15671. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15672. }
  15673. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15674. }
  15675. }
  15676. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15677. }
  15678. else {
  15679. texture.generateMipMaps = !noMipmap;
  15680. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15681. }
  15682. texture.isReady = true;
  15683. // this.resetTextureCache();
  15684. scene._removePendingData(texture);
  15685. if (onLoad) {
  15686. onLoad();
  15687. }
  15688. };
  15689. this._loadFile(url, function (data) {
  15690. internalCallback(data);
  15691. }, undefined, scene.database, true, onerror);
  15692. return texture;
  15693. };
  15694. ;
  15695. /**
  15696. * Update a raw 3D texture
  15697. * @param texture defines the texture to update
  15698. * @param data defines the data to store
  15699. * @param format defines the data format
  15700. * @param invertY defines if data must be stored with Y axis inverted
  15701. * @param compression defines the used compression (can be null)
  15702. */
  15703. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15704. if (compression === void 0) { compression = null; }
  15705. var internalFormat = this._getInternalFormat(format);
  15706. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15708. if (!this._doNotHandleContextLost) {
  15709. texture._bufferView = data;
  15710. texture.format = format;
  15711. texture.invertY = invertY;
  15712. texture._compression = compression;
  15713. }
  15714. if (texture.width % 4 !== 0) {
  15715. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15716. }
  15717. if (compression && data) {
  15718. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15719. }
  15720. else {
  15721. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15722. }
  15723. if (texture.generateMipMaps) {
  15724. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15725. }
  15726. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15727. // this.resetTextureCache();
  15728. texture.isReady = true;
  15729. };
  15730. /**
  15731. * Creates a new raw 3D texture
  15732. * @param data defines the data used to create the texture
  15733. * @param width defines the width of the texture
  15734. * @param height defines the height of the texture
  15735. * @param depth defines the depth of the texture
  15736. * @param format defines the format of the texture
  15737. * @param generateMipMaps defines if the engine must generate mip levels
  15738. * @param invertY defines if data must be stored with Y axis inverted
  15739. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15740. * @param compression defines the compressed used (can be null)
  15741. * @returns a new raw 3D texture (stored in an InternalTexture)
  15742. */
  15743. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15744. if (compression === void 0) { compression = null; }
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15746. texture.baseWidth = width;
  15747. texture.baseHeight = height;
  15748. texture.baseDepth = depth;
  15749. texture.width = width;
  15750. texture.height = height;
  15751. texture.depth = depth;
  15752. texture.format = format;
  15753. texture.generateMipMaps = generateMipMaps;
  15754. texture.samplingMode = samplingMode;
  15755. texture.is3D = true;
  15756. if (!this._doNotHandleContextLost) {
  15757. texture._bufferView = data;
  15758. }
  15759. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15760. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15761. // Filters
  15762. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15763. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15764. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15765. if (generateMipMaps) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15769. this._internalTexturesCache.push(texture);
  15770. return texture;
  15771. };
  15772. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15773. var gl = this._gl;
  15774. if (!gl) {
  15775. return;
  15776. }
  15777. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15780. if (!noMipmap && !isCompressed) {
  15781. gl.generateMipmap(gl.TEXTURE_2D);
  15782. }
  15783. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15784. // this.resetTextureCache();
  15785. if (scene) {
  15786. scene._removePendingData(texture);
  15787. }
  15788. texture.onLoadedObservable.notifyObservers(texture);
  15789. texture.onLoadedObservable.clear();
  15790. };
  15791. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15792. var _this = this;
  15793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15794. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15795. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15796. var gl = this._gl;
  15797. if (!gl) {
  15798. return;
  15799. }
  15800. if (!texture._webGLTexture) {
  15801. // this.resetTextureCache();
  15802. if (scene) {
  15803. scene._removePendingData(texture);
  15804. }
  15805. return;
  15806. }
  15807. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15809. texture.baseWidth = width;
  15810. texture.baseHeight = height;
  15811. texture.width = potWidth;
  15812. texture.height = potHeight;
  15813. texture.isReady = true;
  15814. if (processFunction(potWidth, potHeight, function () {
  15815. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15816. })) {
  15817. // Returning as texture needs extra async steps
  15818. return;
  15819. }
  15820. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15821. };
  15822. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15823. // Create new RGBA data container.
  15824. var rgbaData;
  15825. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15826. rgbaData = new Float32Array(width * height * 4);
  15827. }
  15828. else {
  15829. rgbaData = new Uint32Array(width * height * 4);
  15830. }
  15831. // Convert each pixel.
  15832. for (var x = 0; x < width; x++) {
  15833. for (var y = 0; y < height; y++) {
  15834. var index = (y * width + x) * 3;
  15835. var newIndex = (y * width + x) * 4;
  15836. // Map Old Value to new value.
  15837. rgbaData[newIndex + 0] = rgbData[index + 0];
  15838. rgbaData[newIndex + 1] = rgbData[index + 1];
  15839. rgbaData[newIndex + 2] = rgbData[index + 2];
  15840. // Add fully opaque alpha channel.
  15841. rgbaData[newIndex + 3] = 1;
  15842. }
  15843. }
  15844. return rgbaData;
  15845. };
  15846. /** @ignore */
  15847. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15848. var gl = this._gl;
  15849. if (texture._framebuffer) {
  15850. gl.deleteFramebuffer(texture._framebuffer);
  15851. texture._framebuffer = null;
  15852. }
  15853. if (texture._depthStencilBuffer) {
  15854. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15855. texture._depthStencilBuffer = null;
  15856. }
  15857. if (texture._MSAAFramebuffer) {
  15858. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15859. texture._MSAAFramebuffer = null;
  15860. }
  15861. if (texture._MSAARenderBuffer) {
  15862. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15863. texture._MSAARenderBuffer = null;
  15864. }
  15865. };
  15866. /** @ignore */
  15867. Engine.prototype._releaseTexture = function (texture) {
  15868. var gl = this._gl;
  15869. this._releaseFramebufferObjects(texture);
  15870. gl.deleteTexture(texture._webGLTexture);
  15871. // Unbind channels
  15872. this.unbindAllTextures();
  15873. var index = this._internalTexturesCache.indexOf(texture);
  15874. if (index !== -1) {
  15875. this._internalTexturesCache.splice(index, 1);
  15876. }
  15877. // Integrated fixed lod samplers.
  15878. if (texture._lodTextureHigh) {
  15879. texture._lodTextureHigh.dispose();
  15880. }
  15881. if (texture._lodTextureMid) {
  15882. texture._lodTextureMid.dispose();
  15883. }
  15884. if (texture._lodTextureLow) {
  15885. texture._lodTextureLow.dispose();
  15886. }
  15887. // Set output texture of post process to null if the texture has been released/disposed
  15888. this.scenes.forEach(function (scene) {
  15889. scene.postProcesses.forEach(function (postProcess) {
  15890. if (postProcess._outputTexture == texture) {
  15891. postProcess._outputTexture = null;
  15892. }
  15893. });
  15894. scene.cameras.forEach(function (camera) {
  15895. camera._postProcesses.forEach(function (postProcess) {
  15896. if (postProcess) {
  15897. if (postProcess._outputTexture == texture) {
  15898. postProcess._outputTexture = null;
  15899. }
  15900. }
  15901. });
  15902. });
  15903. });
  15904. };
  15905. Engine.prototype.setProgram = function (program) {
  15906. if (this._currentProgram !== program) {
  15907. this._gl.useProgram(program);
  15908. this._currentProgram = program;
  15909. }
  15910. };
  15911. /**
  15912. * Binds an effect to the webGL context
  15913. * @param effect defines the effect to bind
  15914. */
  15915. Engine.prototype.bindSamplers = function (effect) {
  15916. this.setProgram(effect.getProgram());
  15917. var samplers = effect.getSamplers();
  15918. for (var index = 0; index < samplers.length; index++) {
  15919. var uniform = effect.getUniform(samplers[index]);
  15920. if (uniform) {
  15921. this._boundUniforms[index] = uniform;
  15922. }
  15923. }
  15924. this._currentEffect = null;
  15925. };
  15926. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15927. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15928. return;
  15929. }
  15930. // Remove
  15931. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15932. // Bind last to it
  15933. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15934. // Bind to dummy
  15935. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15936. };
  15937. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15938. if (!internalTexture) {
  15939. return -1;
  15940. }
  15941. internalTexture._initialSlot = channel;
  15942. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  15943. if (channel !== internalTexture._designatedSlot) {
  15944. this._textureCollisions.addCount(1, false);
  15945. }
  15946. }
  15947. else {
  15948. if (channel !== internalTexture._designatedSlot) {
  15949. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  15950. return internalTexture._designatedSlot;
  15951. }
  15952. else {
  15953. // No slot for this texture, let's pick a new one (if we find a free slot)
  15954. if (this._nextFreeTextureSlots.length) {
  15955. return this._nextFreeTextureSlots[0];
  15956. }
  15957. // We need to recycle the oldest bound texture, sorry.
  15958. this._textureCollisions.addCount(1, false);
  15959. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15960. }
  15961. }
  15962. }
  15963. return channel;
  15964. };
  15965. Engine.prototype._linkTrackers = function (previous, next) {
  15966. previous.next = next;
  15967. next.previous = previous;
  15968. };
  15969. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15970. var currentSlot = internalTexture._designatedSlot;
  15971. if (currentSlot === -1) {
  15972. return -1;
  15973. }
  15974. internalTexture._designatedSlot = -1;
  15975. if (this.disableTextureBindingOptimization) {
  15976. return -1;
  15977. }
  15978. // Remove from bound list
  15979. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15980. // Free the slot
  15981. this._boundTexturesCache[currentSlot] = null;
  15982. this._nextFreeTextureSlots.push(currentSlot);
  15983. return currentSlot;
  15984. };
  15985. Engine.prototype._activateCurrentTexture = function () {
  15986. if (this._currentTextureChannel !== this._activeChannel) {
  15987. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15988. this._currentTextureChannel = this._activeChannel;
  15989. }
  15990. };
  15991. /** @ignore */
  15992. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  15993. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15994. if (force === void 0) { force = false; }
  15995. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15996. this._activeChannel = texture._designatedSlot;
  15997. }
  15998. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15999. var isTextureForRendering = texture && texture._initialSlot > -1;
  16000. if (currentTextureBound !== texture || force) {
  16001. if (currentTextureBound) {
  16002. this._removeDesignatedSlot(currentTextureBound);
  16003. }
  16004. this._activateCurrentTexture();
  16005. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16006. this._boundTexturesCache[this._activeChannel] = texture;
  16007. if (texture) {
  16008. if (!this.disableTextureBindingOptimization) {
  16009. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16010. if (slotIndex > -1) {
  16011. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16012. }
  16013. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16014. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16015. }
  16016. texture._designatedSlot = this._activeChannel;
  16017. }
  16018. }
  16019. else if (forTextureDataUpdate) {
  16020. this._activateCurrentTexture();
  16021. }
  16022. if (isTextureForRendering && !forTextureDataUpdate) {
  16023. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16024. }
  16025. };
  16026. /** @ignore */
  16027. Engine.prototype._bindTexture = function (channel, texture) {
  16028. if (channel < 0) {
  16029. return;
  16030. }
  16031. if (texture) {
  16032. channel = this._getCorrectTextureChannel(channel, texture);
  16033. }
  16034. this._activeChannel = channel;
  16035. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16036. };
  16037. /**
  16038. * Sets a texture to the webGL context from a postprocess
  16039. * @param channel defines the channel to use
  16040. * @param postProcess defines the source postprocess
  16041. */
  16042. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16043. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16044. };
  16045. /**
  16046. * Binds the output of the passed in post process to the texture channel specified
  16047. * @param channel The channel the texture should be bound to
  16048. * @param postProcess The post process which's output should be bound
  16049. */
  16050. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16051. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16052. };
  16053. /**
  16054. * Unbind all textures from the webGL context
  16055. */
  16056. Engine.prototype.unbindAllTextures = function () {
  16057. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16058. this._activeChannel = channel;
  16059. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16061. if (this.webGLVersion > 1) {
  16062. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16063. }
  16064. }
  16065. };
  16066. /**
  16067. * Sets a texture to the according uniform.
  16068. * @param channel The texture channel
  16069. * @param uniform The uniform to set
  16070. * @param texture The texture to apply
  16071. */
  16072. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16073. if (channel < 0) {
  16074. return;
  16075. }
  16076. if (uniform) {
  16077. this._boundUniforms[channel] = uniform;
  16078. }
  16079. this._setTexture(channel, texture);
  16080. };
  16081. /**
  16082. * Sets a depth stencil texture from a render target to the according uniform.
  16083. * @param channel The texture channel
  16084. * @param uniform The uniform to set
  16085. * @param texture The render target texture containing the depth stencil texture to apply
  16086. */
  16087. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16088. if (channel < 0) {
  16089. return;
  16090. }
  16091. if (uniform) {
  16092. this._boundUniforms[channel] = uniform;
  16093. }
  16094. if (!texture || !texture.depthStencilTexture) {
  16095. this._setTexture(channel, null);
  16096. }
  16097. else {
  16098. this._setTexture(channel, texture, false, true);
  16099. }
  16100. };
  16101. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16102. var uniform = this._boundUniforms[sourceSlot];
  16103. if (uniform._currentState === destination) {
  16104. return;
  16105. }
  16106. this._gl.uniform1i(uniform, destination);
  16107. uniform._currentState = destination;
  16108. };
  16109. Engine.prototype._getTextureWrapMode = function (mode) {
  16110. switch (mode) {
  16111. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16112. return this._gl.REPEAT;
  16113. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16114. return this._gl.CLAMP_TO_EDGE;
  16115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16116. return this._gl.MIRRORED_REPEAT;
  16117. }
  16118. return this._gl.REPEAT;
  16119. };
  16120. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16121. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16122. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16123. // Not ready?
  16124. if (!texture) {
  16125. if (this._boundTexturesCache[channel] != null) {
  16126. this._activeChannel = channel;
  16127. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16129. if (this.webGLVersion > 1) {
  16130. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16131. }
  16132. }
  16133. return false;
  16134. }
  16135. // Video
  16136. if (texture.video) {
  16137. this._activeChannel = channel;
  16138. texture.update();
  16139. }
  16140. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16141. texture.delayLoad();
  16142. return false;
  16143. }
  16144. var internalTexture;
  16145. if (depthStencilTexture) {
  16146. internalTexture = texture.depthStencilTexture;
  16147. }
  16148. else if (texture.isReady()) {
  16149. internalTexture = texture.getInternalTexture();
  16150. }
  16151. else if (texture.isCube) {
  16152. internalTexture = this.emptyCubeTexture;
  16153. }
  16154. else if (texture.is3D) {
  16155. internalTexture = this.emptyTexture3D;
  16156. }
  16157. else {
  16158. internalTexture = this.emptyTexture;
  16159. }
  16160. if (!isPartOfTextureArray) {
  16161. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16162. }
  16163. var needToBind = true;
  16164. if (this._boundTexturesCache[channel] === internalTexture) {
  16165. this._moveBoundTextureOnTop(internalTexture);
  16166. if (!isPartOfTextureArray) {
  16167. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16168. }
  16169. needToBind = false;
  16170. }
  16171. this._activeChannel = channel;
  16172. if (internalTexture && internalTexture.is3D) {
  16173. if (needToBind) {
  16174. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16175. }
  16176. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16177. internalTexture._cachedWrapU = texture.wrapU;
  16178. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16179. }
  16180. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16181. internalTexture._cachedWrapV = texture.wrapV;
  16182. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16183. }
  16184. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16185. internalTexture._cachedWrapR = texture.wrapR;
  16186. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16187. }
  16188. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16189. }
  16190. else if (internalTexture && internalTexture.isCube) {
  16191. if (needToBind) {
  16192. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16193. }
  16194. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16195. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16196. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16197. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16198. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16199. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16200. }
  16201. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16202. }
  16203. else {
  16204. if (needToBind) {
  16205. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16206. }
  16207. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16208. internalTexture._cachedWrapU = texture.wrapU;
  16209. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16210. }
  16211. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16212. internalTexture._cachedWrapV = texture.wrapV;
  16213. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16214. }
  16215. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16216. }
  16217. return true;
  16218. };
  16219. /**
  16220. * Sets an array of texture to the webGL context
  16221. * @param channel defines the channel where the texture array must be set
  16222. * @param uniform defines the associated uniform location
  16223. * @param textures defines the array of textures to bind
  16224. */
  16225. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16226. if (channel < 0 || !uniform) {
  16227. return;
  16228. }
  16229. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16230. this._textureUnits = new Int32Array(textures.length);
  16231. }
  16232. for (var i = 0; i < textures.length; i++) {
  16233. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16234. }
  16235. this._gl.uniform1iv(uniform, this._textureUnits);
  16236. for (var index = 0; index < textures.length; index++) {
  16237. this._setTexture(this._textureUnits[index], textures[index], true);
  16238. }
  16239. };
  16240. /** @ignore */
  16241. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16242. var internalTexture = texture.getInternalTexture();
  16243. if (!internalTexture) {
  16244. return;
  16245. }
  16246. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16247. var value = texture.anisotropicFilteringLevel;
  16248. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16249. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16250. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16251. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16252. }
  16253. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16254. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16255. internalTexture._cachedAnisotropicFilteringLevel = value;
  16256. }
  16257. };
  16258. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16259. this._bindTextureDirectly(target, texture, true, true);
  16260. this._gl.texParameterf(target, parameter, value);
  16261. };
  16262. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16263. if (texture) {
  16264. this._bindTextureDirectly(target, texture, true, true);
  16265. }
  16266. this._gl.texParameteri(target, parameter, value);
  16267. };
  16268. /**
  16269. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16270. * @param x defines the x coordinate of the rectangle where pixels must be read
  16271. * @param y defines the y coordinate of the rectangle where pixels must be read
  16272. * @param width defines the width of the rectangle where pixels must be read
  16273. * @param height defines the height of the rectangle where pixels must be read
  16274. * @returns a Uint8Array containing RGBA colors
  16275. */
  16276. Engine.prototype.readPixels = function (x, y, width, height) {
  16277. var data = new Uint8Array(height * width * 4);
  16278. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16279. return data;
  16280. };
  16281. /**
  16282. * Add an externaly attached data from its key.
  16283. * This method call will fail and return false, if such key already exists.
  16284. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16285. * @param key the unique key that identifies the data
  16286. * @param data the data object to associate to the key for this Engine instance
  16287. * @return true if no such key were already present and the data was added successfully, false otherwise
  16288. */
  16289. Engine.prototype.addExternalData = function (key, data) {
  16290. if (!this._externalData) {
  16291. this._externalData = new BABYLON.StringDictionary();
  16292. }
  16293. return this._externalData.add(key, data);
  16294. };
  16295. /**
  16296. * Get an externaly attached data from its key
  16297. * @param key the unique key that identifies the data
  16298. * @return the associated data, if present (can be null), or undefined if not present
  16299. */
  16300. Engine.prototype.getExternalData = function (key) {
  16301. if (!this._externalData) {
  16302. this._externalData = new BABYLON.StringDictionary();
  16303. }
  16304. return this._externalData.get(key);
  16305. };
  16306. /**
  16307. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16308. * @param key the unique key that identifies the data
  16309. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16310. * @return the associated data, can be null if the factory returned null.
  16311. */
  16312. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16313. if (!this._externalData) {
  16314. this._externalData = new BABYLON.StringDictionary();
  16315. }
  16316. return this._externalData.getOrAddWithFactory(key, factory);
  16317. };
  16318. /**
  16319. * Remove an externaly attached data from the Engine instance
  16320. * @param key the unique key that identifies the data
  16321. * @return true if the data was successfully removed, false if it doesn't exist
  16322. */
  16323. Engine.prototype.removeExternalData = function (key) {
  16324. if (!this._externalData) {
  16325. this._externalData = new BABYLON.StringDictionary();
  16326. }
  16327. return this._externalData.remove(key);
  16328. };
  16329. /**
  16330. * Unbind all vertex attributes from the webGL context
  16331. */
  16332. Engine.prototype.unbindAllAttributes = function () {
  16333. if (this._mustWipeVertexAttributes) {
  16334. this._mustWipeVertexAttributes = false;
  16335. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16336. this._gl.disableVertexAttribArray(i);
  16337. this._vertexAttribArraysEnabled[i] = false;
  16338. this._currentBufferPointers[i].active = false;
  16339. }
  16340. return;
  16341. }
  16342. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16343. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16344. continue;
  16345. }
  16346. this._gl.disableVertexAttribArray(i);
  16347. this._vertexAttribArraysEnabled[i] = false;
  16348. this._currentBufferPointers[i].active = false;
  16349. }
  16350. };
  16351. /**
  16352. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16353. */
  16354. Engine.prototype.releaseEffects = function () {
  16355. for (var name in this._compiledEffects) {
  16356. this._deleteProgram(this._compiledEffects[name]._program);
  16357. }
  16358. this._compiledEffects = {};
  16359. };
  16360. /**
  16361. * Dispose and release all associated resources
  16362. */
  16363. Engine.prototype.dispose = function () {
  16364. this.hideLoadingUI();
  16365. this.stopRenderLoop();
  16366. // Release postProcesses
  16367. while (this.postProcesses.length) {
  16368. this.postProcesses[0].dispose();
  16369. }
  16370. // Empty texture
  16371. if (this._emptyTexture) {
  16372. this._releaseTexture(this._emptyTexture);
  16373. this._emptyTexture = null;
  16374. }
  16375. if (this._emptyCubeTexture) {
  16376. this._releaseTexture(this._emptyCubeTexture);
  16377. this._emptyCubeTexture = null;
  16378. }
  16379. // Rescale PP
  16380. if (this._rescalePostProcess) {
  16381. this._rescalePostProcess.dispose();
  16382. }
  16383. // Release scenes
  16384. while (this.scenes.length) {
  16385. this.scenes[0].dispose();
  16386. }
  16387. // Release audio engine
  16388. if (Engine.audioEngine) {
  16389. Engine.audioEngine.dispose();
  16390. }
  16391. // Release effects
  16392. this.releaseEffects();
  16393. // Unbind
  16394. this.unbindAllAttributes();
  16395. this._boundUniforms = [];
  16396. if (this._dummyFramebuffer) {
  16397. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16398. }
  16399. //WebVR
  16400. this.disableVR();
  16401. // Events
  16402. if (BABYLON.Tools.IsWindowObjectExist()) {
  16403. window.removeEventListener("blur", this._onBlur);
  16404. window.removeEventListener("focus", this._onFocus);
  16405. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16406. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16407. if (this._renderingCanvas) {
  16408. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16409. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16410. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16411. if (!this._doNotHandleContextLost) {
  16412. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16413. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16414. }
  16415. }
  16416. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16417. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16418. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16419. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16420. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16421. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16422. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16423. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16424. if (this._onVrDisplayConnect) {
  16425. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16426. if (this._onVrDisplayDisconnect) {
  16427. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16428. }
  16429. if (this._onVrDisplayPresentChange) {
  16430. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16431. }
  16432. this._onVrDisplayConnect = null;
  16433. this._onVrDisplayDisconnect = null;
  16434. }
  16435. }
  16436. // Remove from Instances
  16437. var index = Engine.Instances.indexOf(this);
  16438. if (index >= 0) {
  16439. Engine.Instances.splice(index, 1);
  16440. }
  16441. this._workingCanvas = null;
  16442. this._workingContext = null;
  16443. this._currentBufferPointers = [];
  16444. this._renderingCanvas = null;
  16445. this._currentProgram = null;
  16446. this._bindedRenderFunction = null;
  16447. this.onResizeObservable.clear();
  16448. this.onCanvasBlurObservable.clear();
  16449. this.onCanvasFocusObservable.clear();
  16450. this.onCanvasPointerOutObservable.clear();
  16451. this.onBeginFrameObservable.clear();
  16452. this.onEndFrameObservable.clear();
  16453. BABYLON.Effect.ResetCache();
  16454. // Abort active requests
  16455. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16456. var request = _a[_i];
  16457. request.abort();
  16458. }
  16459. };
  16460. // Loading screen
  16461. /**
  16462. * Display the loading screen
  16463. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16464. */
  16465. Engine.prototype.displayLoadingUI = function () {
  16466. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16467. return;
  16468. }
  16469. var loadingScreen = this.loadingScreen;
  16470. if (loadingScreen) {
  16471. loadingScreen.displayLoadingUI();
  16472. }
  16473. };
  16474. /**
  16475. * Hide the loading screen
  16476. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16477. */
  16478. Engine.prototype.hideLoadingUI = function () {
  16479. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16480. return;
  16481. }
  16482. var loadingScreen = this.loadingScreen;
  16483. if (loadingScreen) {
  16484. loadingScreen.hideLoadingUI();
  16485. }
  16486. };
  16487. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16488. /**
  16489. * Gets the current loading screen object
  16490. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16491. */
  16492. get: function () {
  16493. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16494. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16495. return this._loadingScreen;
  16496. },
  16497. /**
  16498. * Sets the current loading screen object
  16499. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16500. */
  16501. set: function (loadingScreen) {
  16502. this._loadingScreen = loadingScreen;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16508. /**
  16509. * Sets the current loading screen text
  16510. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16511. */
  16512. set: function (text) {
  16513. this.loadingScreen.loadingUIText = text;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16519. /**
  16520. * Sets the current loading screen background color
  16521. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16522. */
  16523. set: function (color) {
  16524. this.loadingScreen.loadingUIBackgroundColor = color;
  16525. },
  16526. enumerable: true,
  16527. configurable: true
  16528. });
  16529. /**
  16530. * Attach a new callback raised when context lost event is fired
  16531. * @param callback defines the callback to call
  16532. */
  16533. Engine.prototype.attachContextLostEvent = function (callback) {
  16534. if (this._renderingCanvas) {
  16535. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16536. }
  16537. };
  16538. /**
  16539. * Attach a new callback raised when context restored event is fired
  16540. * @param callback defines the callback to call
  16541. */
  16542. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16543. if (this._renderingCanvas) {
  16544. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16545. }
  16546. };
  16547. /**
  16548. * Gets the source code of the vertex shader associated with a specific webGL program
  16549. * @param program defines the program to use
  16550. * @returns a string containing the source code of the vertex shader associated with the program
  16551. */
  16552. Engine.prototype.getVertexShaderSource = function (program) {
  16553. var shaders = this._gl.getAttachedShaders(program);
  16554. if (!shaders) {
  16555. return null;
  16556. }
  16557. return this._gl.getShaderSource(shaders[0]);
  16558. };
  16559. /**
  16560. * Gets the source code of the fragment shader associated with a specific webGL program
  16561. * @param program defines the program to use
  16562. * @returns a string containing the source code of the fragment shader associated with the program
  16563. */
  16564. Engine.prototype.getFragmentShaderSource = function (program) {
  16565. var shaders = this._gl.getAttachedShaders(program);
  16566. if (!shaders) {
  16567. return null;
  16568. }
  16569. return this._gl.getShaderSource(shaders[1]);
  16570. };
  16571. /**
  16572. * Get the current error code of the webGL context
  16573. * @returns the error code
  16574. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16575. */
  16576. Engine.prototype.getError = function () {
  16577. return this._gl.getError();
  16578. };
  16579. // FPS
  16580. /**
  16581. * Gets the current framerate
  16582. * @returns a number representing the framerate
  16583. */
  16584. Engine.prototype.getFps = function () {
  16585. return this._fps;
  16586. };
  16587. /**
  16588. * Gets the time spent between current and previous frame
  16589. * @returns a number representing the delta time in ms
  16590. */
  16591. Engine.prototype.getDeltaTime = function () {
  16592. return this._deltaTime;
  16593. };
  16594. Engine.prototype._measureFps = function () {
  16595. this._performanceMonitor.sampleFrame();
  16596. this._fps = this._performanceMonitor.averageFPS;
  16597. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16598. };
  16599. /** @ignore */
  16600. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16601. if (faceIndex === void 0) { faceIndex = -1; }
  16602. var gl = this._gl;
  16603. if (!this._dummyFramebuffer) {
  16604. var dummy = gl.createFramebuffer();
  16605. if (!dummy) {
  16606. throw new Error("Unable to create dummy framebuffer");
  16607. }
  16608. this._dummyFramebuffer = dummy;
  16609. }
  16610. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16611. if (faceIndex > -1) {
  16612. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16613. }
  16614. else {
  16615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16616. }
  16617. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16618. var buffer;
  16619. switch (readType) {
  16620. case gl.UNSIGNED_BYTE:
  16621. buffer = new Uint8Array(4 * width * height);
  16622. readType = gl.UNSIGNED_BYTE;
  16623. break;
  16624. default:
  16625. buffer = new Float32Array(4 * width * height);
  16626. readType = gl.FLOAT;
  16627. break;
  16628. }
  16629. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16630. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16631. return buffer;
  16632. };
  16633. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16634. if (this._webGLVersion > 1) {
  16635. return this._caps.colorBufferFloat;
  16636. }
  16637. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16638. };
  16639. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16640. if (this._webGLVersion > 1) {
  16641. return this._caps.colorBufferFloat;
  16642. }
  16643. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16644. };
  16645. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16646. Engine.prototype._canRenderToFramebuffer = function (type) {
  16647. var gl = this._gl;
  16648. //clear existing errors
  16649. while (gl.getError() !== gl.NO_ERROR) { }
  16650. var successful = true;
  16651. var texture = gl.createTexture();
  16652. gl.bindTexture(gl.TEXTURE_2D, texture);
  16653. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16656. var fb = gl.createFramebuffer();
  16657. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16659. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16660. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16661. successful = successful && (gl.getError() === gl.NO_ERROR);
  16662. //try render by clearing frame buffer's color buffer
  16663. if (successful) {
  16664. gl.clear(gl.COLOR_BUFFER_BIT);
  16665. successful = successful && (gl.getError() === gl.NO_ERROR);
  16666. }
  16667. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16668. if (successful) {
  16669. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16670. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16671. var readFormat = gl.RGBA;
  16672. var readType = gl.UNSIGNED_BYTE;
  16673. var buffer = new Uint8Array(4);
  16674. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16675. successful = successful && (gl.getError() === gl.NO_ERROR);
  16676. }
  16677. //clean up
  16678. gl.deleteTexture(texture);
  16679. gl.deleteFramebuffer(fb);
  16680. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16681. //clear accumulated errors
  16682. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16683. return successful;
  16684. };
  16685. /** @ignore */
  16686. Engine.prototype._getWebGLTextureType = function (type) {
  16687. if (type === Engine.TEXTURETYPE_FLOAT) {
  16688. return this._gl.FLOAT;
  16689. }
  16690. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16691. // Add Half Float Constant.
  16692. return this._gl.HALF_FLOAT_OES;
  16693. }
  16694. return this._gl.UNSIGNED_BYTE;
  16695. };
  16696. ;
  16697. Engine.prototype._getInternalFormat = function (format) {
  16698. var internalFormat = this._gl.RGBA;
  16699. switch (format) {
  16700. case Engine.TEXTUREFORMAT_ALPHA:
  16701. internalFormat = this._gl.ALPHA;
  16702. break;
  16703. case Engine.TEXTUREFORMAT_LUMINANCE:
  16704. internalFormat = this._gl.LUMINANCE;
  16705. break;
  16706. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16707. internalFormat = this._gl.LUMINANCE_ALPHA;
  16708. break;
  16709. case Engine.TEXTUREFORMAT_RGB:
  16710. case Engine.TEXTUREFORMAT_RGB32F:
  16711. internalFormat = this._gl.RGB;
  16712. break;
  16713. case Engine.TEXTUREFORMAT_RGBA:
  16714. case Engine.TEXTUREFORMAT_RGBA32F:
  16715. internalFormat = this._gl.RGBA;
  16716. break;
  16717. case Engine.TEXTUREFORMAT_R32F:
  16718. internalFormat = this._gl.RED;
  16719. break;
  16720. case Engine.TEXTUREFORMAT_RG32F:
  16721. internalFormat = this._gl.RG;
  16722. break;
  16723. }
  16724. return internalFormat;
  16725. };
  16726. /** @ignore */
  16727. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16728. if (this._webGLVersion === 1) {
  16729. if (format) {
  16730. switch (format) {
  16731. case Engine.TEXTUREFORMAT_LUMINANCE:
  16732. return this._gl.LUMINANCE;
  16733. }
  16734. }
  16735. return this._gl.RGBA;
  16736. }
  16737. if (type === Engine.TEXTURETYPE_FLOAT) {
  16738. if (format) {
  16739. switch (format) {
  16740. case Engine.TEXTUREFORMAT_R32F:
  16741. return this._gl.R32F;
  16742. case Engine.TEXTUREFORMAT_RG32F:
  16743. return this._gl.RG32F;
  16744. case Engine.TEXTUREFORMAT_RGB32F:
  16745. return this._gl.RGB32F;
  16746. }
  16747. }
  16748. return this._gl.RGBA32F;
  16749. }
  16750. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16751. return this._gl.RGBA16F;
  16752. }
  16753. if (format) {
  16754. switch (format) {
  16755. case Engine.TEXTUREFORMAT_LUMINANCE:
  16756. return this._gl.LUMINANCE;
  16757. }
  16758. }
  16759. return this._gl.RGBA;
  16760. };
  16761. ;
  16762. /** @ignore */
  16763. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16764. if (type === Engine.TEXTURETYPE_FLOAT) {
  16765. return this._gl.RGBA32F;
  16766. }
  16767. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16768. return this._gl.RGBA16F;
  16769. }
  16770. return this._gl.RGBA8;
  16771. };
  16772. ;
  16773. /**
  16774. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16775. * @return the new query
  16776. */
  16777. Engine.prototype.createQuery = function () {
  16778. return this._gl.createQuery();
  16779. };
  16780. /**
  16781. * Delete and release a webGL query
  16782. * @param query defines the query to delete
  16783. * @return the current engine
  16784. */
  16785. Engine.prototype.deleteQuery = function (query) {
  16786. this._gl.deleteQuery(query);
  16787. return this;
  16788. };
  16789. /**
  16790. * Check if a given query has resolved and got its value
  16791. * @param query defines the query to check
  16792. * @returns true if the query got its value
  16793. */
  16794. Engine.prototype.isQueryResultAvailable = function (query) {
  16795. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16796. };
  16797. /**
  16798. * Gets the value of a given query
  16799. * @param query defines the query to check
  16800. * @returns the value of the query
  16801. */
  16802. Engine.prototype.getQueryResult = function (query) {
  16803. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16804. };
  16805. /**
  16806. * Initiates an occlusion query
  16807. * @param algorithmType defines the algorithm to use
  16808. * @param query defines the query to use
  16809. * @returns the current engine
  16810. * @see http://doc.babylonjs.com/features/occlusionquery
  16811. */
  16812. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16813. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16814. this._gl.beginQuery(glAlgorithm, query);
  16815. return this;
  16816. };
  16817. /**
  16818. * Ends an occlusion query
  16819. * @see http://doc.babylonjs.com/features/occlusionquery
  16820. * @param algorithmType defines the algorithm to use
  16821. * @returns the current engine
  16822. */
  16823. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16824. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16825. this._gl.endQuery(glAlgorithm);
  16826. return this;
  16827. };
  16828. /* Time queries */
  16829. Engine.prototype._createTimeQuery = function () {
  16830. var timerQuery = this._caps.timerQuery;
  16831. if (timerQuery.createQueryEXT) {
  16832. return timerQuery.createQueryEXT();
  16833. }
  16834. return this.createQuery();
  16835. };
  16836. Engine.prototype._deleteTimeQuery = function (query) {
  16837. var timerQuery = this._caps.timerQuery;
  16838. if (timerQuery.deleteQueryEXT) {
  16839. timerQuery.deleteQueryEXT(query);
  16840. return;
  16841. }
  16842. this.deleteQuery(query);
  16843. };
  16844. Engine.prototype._getTimeQueryResult = function (query) {
  16845. var timerQuery = this._caps.timerQuery;
  16846. if (timerQuery.getQueryObjectEXT) {
  16847. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16848. }
  16849. return this.getQueryResult(query);
  16850. };
  16851. Engine.prototype._getTimeQueryAvailability = function (query) {
  16852. var timerQuery = this._caps.timerQuery;
  16853. if (timerQuery.getQueryObjectEXT) {
  16854. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16855. }
  16856. return this.isQueryResultAvailable(query);
  16857. };
  16858. /**
  16859. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16860. * Please note that only one query can be issued at a time
  16861. * @returns a time token used to track the time span
  16862. */
  16863. Engine.prototype.startTimeQuery = function () {
  16864. var timerQuery = this._caps.timerQuery;
  16865. if (!timerQuery) {
  16866. return null;
  16867. }
  16868. var token = new BABYLON._TimeToken();
  16869. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16870. if (this._caps.canUseTimestampForTimerQuery) {
  16871. token._startTimeQuery = this._createTimeQuery();
  16872. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16873. }
  16874. else {
  16875. if (this._currentNonTimestampToken) {
  16876. return this._currentNonTimestampToken;
  16877. }
  16878. token._timeElapsedQuery = this._createTimeQuery();
  16879. if (timerQuery.beginQueryEXT) {
  16880. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16881. }
  16882. else {
  16883. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16884. }
  16885. this._currentNonTimestampToken = token;
  16886. }
  16887. return token;
  16888. };
  16889. /**
  16890. * Ends a time query
  16891. * @param token defines the token used to measure the time span
  16892. * @returns the time spent (in ns)
  16893. */
  16894. Engine.prototype.endTimeQuery = function (token) {
  16895. var timerQuery = this._caps.timerQuery;
  16896. if (!timerQuery || !token) {
  16897. return -1;
  16898. }
  16899. if (this._caps.canUseTimestampForTimerQuery) {
  16900. if (!token._startTimeQuery) {
  16901. return -1;
  16902. }
  16903. if (!token._endTimeQuery) {
  16904. token._endTimeQuery = this._createTimeQuery();
  16905. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16906. }
  16907. }
  16908. else if (!token._timeElapsedQueryEnded) {
  16909. if (!token._timeElapsedQuery) {
  16910. return -1;
  16911. }
  16912. if (timerQuery.endQueryEXT) {
  16913. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16914. }
  16915. else {
  16916. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16917. }
  16918. token._timeElapsedQueryEnded = true;
  16919. }
  16920. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16921. var available = false;
  16922. if (token._endTimeQuery) {
  16923. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16924. }
  16925. else if (token._timeElapsedQuery) {
  16926. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16927. }
  16928. if (available && !disjoint) {
  16929. var result = 0;
  16930. if (this._caps.canUseTimestampForTimerQuery) {
  16931. if (!token._startTimeQuery || !token._endTimeQuery) {
  16932. return -1;
  16933. }
  16934. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16935. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16936. result = timeEnd - timeStart;
  16937. this._deleteTimeQuery(token._startTimeQuery);
  16938. this._deleteTimeQuery(token._endTimeQuery);
  16939. token._startTimeQuery = null;
  16940. token._endTimeQuery = null;
  16941. }
  16942. else {
  16943. if (!token._timeElapsedQuery) {
  16944. return -1;
  16945. }
  16946. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16947. this._deleteTimeQuery(token._timeElapsedQuery);
  16948. token._timeElapsedQuery = null;
  16949. token._timeElapsedQueryEnded = false;
  16950. this._currentNonTimestampToken = null;
  16951. }
  16952. return result;
  16953. }
  16954. return -1;
  16955. };
  16956. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16957. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16958. };
  16959. // Transform feedback
  16960. /**
  16961. * Creates a webGL transform feedback object
  16962. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16963. * @returns the webGL transform feedback object
  16964. */
  16965. Engine.prototype.createTransformFeedback = function () {
  16966. return this._gl.createTransformFeedback();
  16967. };
  16968. /**
  16969. * Delete a webGL transform feedback object
  16970. * @param value defines the webGL transform feedback object to delete
  16971. */
  16972. Engine.prototype.deleteTransformFeedback = function (value) {
  16973. this._gl.deleteTransformFeedback(value);
  16974. };
  16975. /**
  16976. * Bind a webGL transform feedback object to the webgl context
  16977. * @param value defines the webGL transform feedback object to bind
  16978. */
  16979. Engine.prototype.bindTransformFeedback = function (value) {
  16980. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16981. };
  16982. /**
  16983. * Begins a transform feedback operation
  16984. * @param usePoints defines if points or triangles must be used
  16985. */
  16986. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16987. if (usePoints === void 0) { usePoints = true; }
  16988. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16989. };
  16990. /**
  16991. * Ends a transform feedback operation
  16992. */
  16993. Engine.prototype.endTransformFeedback = function () {
  16994. this._gl.endTransformFeedback();
  16995. };
  16996. /**
  16997. * Specify the varyings to use with transform feedback
  16998. * @param program defines the associated webGL program
  16999. * @param value defines the list of strings representing the varying names
  17000. */
  17001. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17002. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17003. };
  17004. /**
  17005. * Bind a webGL buffer for a transform feedback operation
  17006. * @param value defines the webGL buffer to bind
  17007. */
  17008. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17009. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17010. };
  17011. /** @ignore */
  17012. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17013. var _this = this;
  17014. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17015. this._activeRequests.push(request);
  17016. request.onCompleteObservable.add(function (request) {
  17017. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17018. });
  17019. return request;
  17020. };
  17021. /** @ignore */
  17022. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17023. var _this = this;
  17024. return new Promise(function (resolve, reject) {
  17025. _this._loadFile(url, function (data) {
  17026. resolve(data);
  17027. }, undefined, database, useArrayBuffer, function (request, exception) {
  17028. reject(exception);
  17029. });
  17030. });
  17031. };
  17032. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17033. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17034. var onload = function (data) {
  17035. loadedFiles[index] = data;
  17036. loadedFiles._internalCount++;
  17037. if (loadedFiles._internalCount === 6) {
  17038. onfinish(loadedFiles);
  17039. }
  17040. };
  17041. var onerror = function (request, exception) {
  17042. if (onErrorCallBack && request) {
  17043. onErrorCallBack(request.status + " " + request.statusText, exception);
  17044. }
  17045. };
  17046. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17047. };
  17048. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17049. if (onError === void 0) { onError = null; }
  17050. var loadedFiles = [];
  17051. loadedFiles._internalCount = 0;
  17052. for (var index = 0; index < 6; index++) {
  17053. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17054. }
  17055. };
  17056. // Statics
  17057. /**
  17058. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17059. * @returns true if the engine can be created
  17060. * @ignoreNaming
  17061. */
  17062. Engine.isSupported = function () {
  17063. try {
  17064. var tempcanvas = document.createElement("canvas");
  17065. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17066. return gl != null && !!window.WebGLRenderingContext;
  17067. }
  17068. catch (e) {
  17069. return false;
  17070. }
  17071. };
  17072. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17073. Engine.ExceptionList = [
  17074. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17075. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17076. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17077. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17078. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17079. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17080. ];
  17081. /** Gets the list of created engines */
  17082. Engine.Instances = new Array();
  17083. // Const statics
  17084. Engine._ALPHA_DISABLE = 0;
  17085. Engine._ALPHA_ADD = 1;
  17086. Engine._ALPHA_COMBINE = 2;
  17087. Engine._ALPHA_SUBTRACT = 3;
  17088. Engine._ALPHA_MULTIPLY = 4;
  17089. Engine._ALPHA_MAXIMIZED = 5;
  17090. Engine._ALPHA_ONEONE = 6;
  17091. Engine._ALPHA_PREMULTIPLIED = 7;
  17092. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17093. Engine._ALPHA_INTERPOLATE = 9;
  17094. Engine._ALPHA_SCREENMODE = 10;
  17095. Engine._DELAYLOADSTATE_NONE = 0;
  17096. Engine._DELAYLOADSTATE_LOADED = 1;
  17097. Engine._DELAYLOADSTATE_LOADING = 2;
  17098. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17099. Engine._TEXTUREFORMAT_ALPHA = 0;
  17100. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17101. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17102. Engine._TEXTUREFORMAT_RGB = 4;
  17103. Engine._TEXTUREFORMAT_RGBA = 5;
  17104. Engine._TEXTUREFORMAT_R32F = 6;
  17105. Engine._TEXTUREFORMAT_RG32F = 7;
  17106. Engine._TEXTUREFORMAT_RGB32F = 8;
  17107. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17108. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17109. Engine._TEXTURETYPE_FLOAT = 1;
  17110. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17111. // Depht or Stencil test Constants.
  17112. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17113. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17114. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17115. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17116. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17117. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17118. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17119. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17120. // Stencil Actions Constants.
  17121. Engine._KEEP = 0x1E00;
  17122. Engine._REPLACE = 0x1E01;
  17123. Engine._INCR = 0x1E02;
  17124. Engine._DECR = 0x1E03;
  17125. Engine._INVERT = 0x150A;
  17126. Engine._INCR_WRAP = 0x8507;
  17127. Engine._DECR_WRAP = 0x8508;
  17128. // Texture rescaling mode
  17129. Engine._SCALEMODE_FLOOR = 1;
  17130. Engine._SCALEMODE_NEAREST = 2;
  17131. Engine._SCALEMODE_CEILING = 3;
  17132. // Updatable statics so stick with vars here
  17133. /**
  17134. * Gets or sets the epsilon value used by collision engine
  17135. */
  17136. Engine.CollisionsEpsilon = 0.001;
  17137. /**
  17138. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17139. */
  17140. Engine.CodeRepository = "src/";
  17141. /**
  17142. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17143. */
  17144. Engine.ShadersRepository = "src/Shaders/";
  17145. return Engine;
  17146. }());
  17147. BABYLON.Engine = Engine;
  17148. })(BABYLON || (BABYLON = {}));
  17149. //# sourceMappingURL=babylon.engine.js.map
  17150. var BABYLON;
  17151. (function (BABYLON) {
  17152. /**
  17153. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17154. */
  17155. var Node = /** @class */ (function () {
  17156. /**
  17157. * Creates a new Node
  17158. * @param {string} name - the name and id to be given to this node
  17159. * @param {BABYLON.Scene} the scene this node will be added to
  17160. */
  17161. function Node(name, scene) {
  17162. if (scene === void 0) { scene = null; }
  17163. /**
  17164. * Gets or sets a string used to store user defined state for the node
  17165. */
  17166. this.state = "";
  17167. /**
  17168. * Gets or sets an object used to store user defined information for the node
  17169. */
  17170. this.metadata = null;
  17171. /**
  17172. * Gets or sets a boolean used to define if the node must be serialized
  17173. */
  17174. this.doNotSerialize = false;
  17175. /** @ignore */
  17176. this._isDisposed = false;
  17177. /**
  17178. * Gets a list of Animations associated with the node
  17179. */
  17180. this.animations = new Array();
  17181. this._ranges = {};
  17182. this._isEnabled = true;
  17183. this._isReady = true;
  17184. /** @ignore */
  17185. this._currentRenderId = -1;
  17186. this._parentRenderId = -1;
  17187. this._childRenderId = -1;
  17188. this._animationPropertiesOverride = null;
  17189. /**
  17190. * An event triggered when the mesh is disposed
  17191. */
  17192. this.onDisposeObservable = new BABYLON.Observable();
  17193. // Behaviors
  17194. this._behaviors = new Array();
  17195. this.name = name;
  17196. this.id = name;
  17197. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17198. this.uniqueId = this._scene.getUniqueId();
  17199. this._initCache();
  17200. }
  17201. /**
  17202. * Gets a boolean indicating if the node has been disposed
  17203. * @returns true if the node was disposed
  17204. */
  17205. Node.prototype.isDisposed = function () {
  17206. return this._isDisposed;
  17207. };
  17208. Object.defineProperty(Node.prototype, "parent", {
  17209. get: function () {
  17210. return this._parentNode;
  17211. },
  17212. /**
  17213. * Gets or sets the parent of the node
  17214. */
  17215. set: function (parent) {
  17216. if (this._parentNode === parent) {
  17217. return;
  17218. }
  17219. // Remove self from list of children of parent
  17220. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17221. var index = this._parentNode._children.indexOf(this);
  17222. if (index !== -1) {
  17223. this._parentNode._children.splice(index, 1);
  17224. }
  17225. }
  17226. // Store new parent
  17227. this._parentNode = parent;
  17228. // Add as child to new parent
  17229. if (this._parentNode) {
  17230. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17231. this._parentNode._children = new Array();
  17232. }
  17233. this._parentNode._children.push(this);
  17234. }
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17240. /**
  17241. * Gets or sets the animation properties override
  17242. */
  17243. get: function () {
  17244. if (!this._animationPropertiesOverride) {
  17245. return this._scene.animationPropertiesOverride;
  17246. }
  17247. return this._animationPropertiesOverride;
  17248. },
  17249. set: function (value) {
  17250. this._animationPropertiesOverride = value;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. /**
  17256. * Gets a string idenfifying the name of the class
  17257. * @returns "Node" string
  17258. */
  17259. Node.prototype.getClassName = function () {
  17260. return "Node";
  17261. };
  17262. Object.defineProperty(Node.prototype, "onDispose", {
  17263. /**
  17264. * Sets a callback that will be raised when the node will be disposed
  17265. */
  17266. set: function (callback) {
  17267. if (this._onDisposeObserver) {
  17268. this.onDisposeObservable.remove(this._onDisposeObserver);
  17269. }
  17270. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. /**
  17276. * Gets the scene of the node
  17277. * @returns a {BABYLON.Scene}
  17278. */
  17279. Node.prototype.getScene = function () {
  17280. return this._scene;
  17281. };
  17282. /**
  17283. * Gets the engine of the node
  17284. * @returns a {BABYLON.Engine}
  17285. */
  17286. Node.prototype.getEngine = function () {
  17287. return this._scene.getEngine();
  17288. };
  17289. /**
  17290. * Attach a behavior to the node
  17291. * @see http://doc.babylonjs.com/features/behaviour
  17292. * @param behavior defines the behavior to attach
  17293. * @returns the current Node
  17294. */
  17295. Node.prototype.addBehavior = function (behavior) {
  17296. var _this = this;
  17297. var index = this._behaviors.indexOf(behavior);
  17298. if (index !== -1) {
  17299. return this;
  17300. }
  17301. behavior.init();
  17302. if (this._scene.isLoading) {
  17303. // We defer the attach when the scene will be loaded
  17304. var observer = this._scene.onDataLoadedObservable.add(function () {
  17305. behavior.attach(_this);
  17306. setTimeout(function () {
  17307. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17308. _this._scene.onDataLoadedObservable.remove(observer);
  17309. }, 0);
  17310. });
  17311. }
  17312. else {
  17313. behavior.attach(this);
  17314. }
  17315. this._behaviors.push(behavior);
  17316. return this;
  17317. };
  17318. /**
  17319. * Remove an attached behavior
  17320. * @see http://doc.babylonjs.com/features/behaviour
  17321. * @param behavior defines the behavior to attach
  17322. * @returns the current Node
  17323. */
  17324. Node.prototype.removeBehavior = function (behavior) {
  17325. var index = this._behaviors.indexOf(behavior);
  17326. if (index === -1) {
  17327. return this;
  17328. }
  17329. this._behaviors[index].detach();
  17330. this._behaviors.splice(index, 1);
  17331. return this;
  17332. };
  17333. Object.defineProperty(Node.prototype, "behaviors", {
  17334. /**
  17335. * Gets the list of attached behaviors
  17336. * @see http://doc.babylonjs.com/features/behaviour
  17337. */
  17338. get: function () {
  17339. return this._behaviors;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. /**
  17345. * Gets an attached behavior by name
  17346. * @param name defines the name of the behavior to look for
  17347. * @see http://doc.babylonjs.com/features/behaviour
  17348. * @returns null if behavior was not found else the requested behavior
  17349. */
  17350. Node.prototype.getBehaviorByName = function (name) {
  17351. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17352. var behavior = _a[_i];
  17353. if (behavior.name === name) {
  17354. return behavior;
  17355. }
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * Returns the world matrix of the node
  17361. * @returns a matrix containing the node's world matrix
  17362. */
  17363. Node.prototype.getWorldMatrix = function () {
  17364. return BABYLON.Matrix.Identity();
  17365. };
  17366. // override it in derived class if you add new variables to the cache
  17367. // and call the parent class method
  17368. /** @ignore */
  17369. Node.prototype._initCache = function () {
  17370. this._cache = {};
  17371. this._cache.parent = undefined;
  17372. };
  17373. /** @ignore */
  17374. Node.prototype.updateCache = function (force) {
  17375. if (!force && this.isSynchronized())
  17376. return;
  17377. this._cache.parent = this.parent;
  17378. this._updateCache();
  17379. };
  17380. // override it in derived class if you add new variables to the cache
  17381. // and call the parent class method if !ignoreParentClass
  17382. /** @ignore */
  17383. Node.prototype._updateCache = function (ignoreParentClass) {
  17384. };
  17385. // override it in derived class if you add new variables to the cache
  17386. /** @ignore */
  17387. Node.prototype._isSynchronized = function () {
  17388. return true;
  17389. };
  17390. /** @ignore */
  17391. Node.prototype._markSyncedWithParent = function () {
  17392. if (this.parent) {
  17393. this._parentRenderId = this.parent._childRenderId;
  17394. }
  17395. };
  17396. /** @ignore */
  17397. Node.prototype.isSynchronizedWithParent = function () {
  17398. if (!this.parent) {
  17399. return true;
  17400. }
  17401. if (this._parentRenderId !== this.parent._childRenderId) {
  17402. return false;
  17403. }
  17404. return this.parent.isSynchronized();
  17405. };
  17406. /** @ignore */
  17407. Node.prototype.isSynchronized = function (updateCache) {
  17408. var check = this.hasNewParent();
  17409. check = check || !this.isSynchronizedWithParent();
  17410. check = check || !this._isSynchronized();
  17411. if (updateCache)
  17412. this.updateCache(true);
  17413. return !check;
  17414. };
  17415. /** @ignore */
  17416. Node.prototype.hasNewParent = function (update) {
  17417. if (this._cache.parent === this.parent)
  17418. return false;
  17419. if (update)
  17420. this._cache.parent = this.parent;
  17421. return true;
  17422. };
  17423. /**
  17424. * Is this node ready to be used/rendered
  17425. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17426. * @return true if the node is ready
  17427. */
  17428. Node.prototype.isReady = function (completeCheck) {
  17429. if (completeCheck === void 0) { completeCheck = false; }
  17430. return this._isReady;
  17431. };
  17432. /**
  17433. * Is this node enabled?
  17434. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17435. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17436. * @return whether this node (and its parent) is enabled
  17437. */
  17438. Node.prototype.isEnabled = function (checkAncestors) {
  17439. if (checkAncestors === void 0) { checkAncestors = true; }
  17440. if (checkAncestors === false) {
  17441. return this._isEnabled;
  17442. }
  17443. if (this._isEnabled === false) {
  17444. return false;
  17445. }
  17446. if (this.parent !== undefined && this.parent !== null) {
  17447. return this.parent.isEnabled(checkAncestors);
  17448. }
  17449. return true;
  17450. };
  17451. /**
  17452. * Set the enabled state of this node
  17453. * @param value defines the new enabled state
  17454. */
  17455. Node.prototype.setEnabled = function (value) {
  17456. this._isEnabled = value;
  17457. };
  17458. /**
  17459. * Is this node a descendant of the given node?
  17460. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17461. * @param ancestor defines the parent node to inspect
  17462. * @returns a boolean indicating if this node is a descendant of the given node
  17463. */
  17464. Node.prototype.isDescendantOf = function (ancestor) {
  17465. if (this.parent) {
  17466. if (this.parent === ancestor) {
  17467. return true;
  17468. }
  17469. return this.parent.isDescendantOf(ancestor);
  17470. }
  17471. return false;
  17472. };
  17473. /** @ignore */
  17474. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17475. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17476. if (!this._children) {
  17477. return;
  17478. }
  17479. for (var index = 0; index < this._children.length; index++) {
  17480. var item = this._children[index];
  17481. if (!predicate || predicate(item)) {
  17482. results.push(item);
  17483. }
  17484. if (!directDescendantsOnly) {
  17485. item._getDescendants(results, false, predicate);
  17486. }
  17487. }
  17488. };
  17489. /**
  17490. * Will return all nodes that have this node as ascendant
  17491. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17492. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17493. * @return all children nodes of all types
  17494. */
  17495. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17496. var results = new Array();
  17497. this._getDescendants(results, directDescendantsOnly, predicate);
  17498. return results;
  17499. };
  17500. /**
  17501. * Get all child-meshes of this node
  17502. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17503. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17504. * @returns an array of {BABYLON.AbstractMesh}
  17505. */
  17506. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17507. var results = [];
  17508. this._getDescendants(results, directDescendantsOnly, function (node) {
  17509. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17510. });
  17511. return results;
  17512. };
  17513. /**
  17514. * Get all child-transformNodes of this node
  17515. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17516. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17517. * @returns an array of {BABYLON.TransformNode}
  17518. */
  17519. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17520. var results = [];
  17521. this._getDescendants(results, directDescendantsOnly, function (node) {
  17522. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17523. });
  17524. return results;
  17525. };
  17526. /**
  17527. * Get all direct children of this node
  17528. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17529. * @returns an array of {BABYLON.Node}
  17530. */
  17531. Node.prototype.getChildren = function (predicate) {
  17532. return this.getDescendants(true, predicate);
  17533. };
  17534. /** @ignore */
  17535. Node.prototype._setReady = function (state) {
  17536. if (state === this._isReady) {
  17537. return;
  17538. }
  17539. if (!state) {
  17540. this._isReady = false;
  17541. return;
  17542. }
  17543. if (this.onReady) {
  17544. this.onReady(this);
  17545. }
  17546. this._isReady = true;
  17547. };
  17548. /**
  17549. * Get an animation by name
  17550. * @param name defines the name of the animation to look for
  17551. * @returns null if not found else the requested animation
  17552. */
  17553. Node.prototype.getAnimationByName = function (name) {
  17554. for (var i = 0; i < this.animations.length; i++) {
  17555. var animation = this.animations[i];
  17556. if (animation.name === name) {
  17557. return animation;
  17558. }
  17559. }
  17560. return null;
  17561. };
  17562. /**
  17563. * Creates an animation range for this node
  17564. * @param name defines the name of the range
  17565. * @param from defines the starting key
  17566. * @param to defines the end key
  17567. */
  17568. Node.prototype.createAnimationRange = function (name, from, to) {
  17569. // check name not already in use
  17570. if (!this._ranges[name]) {
  17571. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17572. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17573. if (this.animations[i]) {
  17574. this.animations[i].createRange(name, from, to);
  17575. }
  17576. }
  17577. }
  17578. };
  17579. /**
  17580. * Delete a specific animation range
  17581. * @param name defines the name of the range to delete
  17582. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17583. */
  17584. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17585. if (deleteFrames === void 0) { deleteFrames = true; }
  17586. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17587. if (this.animations[i]) {
  17588. this.animations[i].deleteRange(name, deleteFrames);
  17589. }
  17590. }
  17591. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17592. };
  17593. /**
  17594. * Get an animation range by name
  17595. * @param name defines the name of the animation range to look for
  17596. * @returns null if not found else the requested animation range
  17597. */
  17598. Node.prototype.getAnimationRange = function (name) {
  17599. return this._ranges[name];
  17600. };
  17601. /**
  17602. * Will start the animation sequence
  17603. * @param name defines the range frames for animation sequence
  17604. * @param loop defines if the animation should loop (false by default)
  17605. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17606. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17607. * @returns the object created for this animation. If range does not exist, it will return null
  17608. */
  17609. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17610. var range = this.getAnimationRange(name);
  17611. if (!range) {
  17612. return null;
  17613. }
  17614. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17615. };
  17616. /**
  17617. * Serialize animation ranges into a JSON compatible object
  17618. * @returns serialization object
  17619. */
  17620. Node.prototype.serializeAnimationRanges = function () {
  17621. var serializationRanges = [];
  17622. for (var name in this._ranges) {
  17623. var localRange = this._ranges[name];
  17624. if (!localRange) {
  17625. continue;
  17626. }
  17627. var range = {};
  17628. range.name = name;
  17629. range.from = localRange.from;
  17630. range.to = localRange.to;
  17631. serializationRanges.push(range);
  17632. }
  17633. return serializationRanges;
  17634. };
  17635. /**
  17636. * Computes the world matrix of the node
  17637. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17638. * @returns the world matrix
  17639. */
  17640. Node.prototype.computeWorldMatrix = function (force) {
  17641. return BABYLON.Matrix.Identity();
  17642. };
  17643. /**
  17644. * Releases resources associated with this node.
  17645. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17646. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17647. */
  17648. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17650. if (!doNotRecurse) {
  17651. var nodes = this.getDescendants(true);
  17652. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17653. var node = nodes_1[_i];
  17654. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17655. }
  17656. }
  17657. else {
  17658. var transformNodes = this.getChildTransformNodes(true);
  17659. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17660. var transformNode = transformNodes_1[_a];
  17661. transformNode.parent = null;
  17662. transformNode.computeWorldMatrix(true);
  17663. }
  17664. }
  17665. this.parent = null;
  17666. // Callback
  17667. this.onDisposeObservable.notifyObservers(this);
  17668. this.onDisposeObservable.clear();
  17669. // Behaviors
  17670. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17671. var behavior = _c[_b];
  17672. behavior.detach();
  17673. }
  17674. this._behaviors = [];
  17675. this._isDisposed = true;
  17676. };
  17677. /**
  17678. * Parse animation range data from a serialization object and store them into a given node
  17679. * @param node defines where to store the animation ranges
  17680. * @param parsedNode defines the serialization object to read data from
  17681. * @param scene defines the hosting scene
  17682. */
  17683. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17684. if (parsedNode.ranges) {
  17685. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17686. var data = parsedNode.ranges[index];
  17687. node.createAnimationRange(data.name, data.from, data.to);
  17688. }
  17689. }
  17690. };
  17691. __decorate([
  17692. BABYLON.serialize()
  17693. ], Node.prototype, "name", void 0);
  17694. __decorate([
  17695. BABYLON.serialize()
  17696. ], Node.prototype, "id", void 0);
  17697. __decorate([
  17698. BABYLON.serialize()
  17699. ], Node.prototype, "uniqueId", void 0);
  17700. __decorate([
  17701. BABYLON.serialize()
  17702. ], Node.prototype, "state", void 0);
  17703. __decorate([
  17704. BABYLON.serialize()
  17705. ], Node.prototype, "metadata", void 0);
  17706. return Node;
  17707. }());
  17708. BABYLON.Node = Node;
  17709. })(BABYLON || (BABYLON = {}));
  17710. //# sourceMappingURL=babylon.node.js.map
  17711. var BABYLON;
  17712. (function (BABYLON) {
  17713. var BoundingSphere = /** @class */ (function () {
  17714. /**
  17715. * Creates a new bounding sphere
  17716. * @param min defines the minimum vector (in local space)
  17717. * @param max defines the maximum vector (in local space)
  17718. */
  17719. function BoundingSphere(min, max) {
  17720. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17721. this.reConstruct(min, max);
  17722. }
  17723. /**
  17724. * Recreates the entire bounding sphere from scratch
  17725. * @param min defines the new minimum vector (in local space)
  17726. * @param max defines the new maximum vector (in local space)
  17727. */
  17728. BoundingSphere.prototype.reConstruct = function (min, max) {
  17729. this.minimum = min.clone();
  17730. this.maximum = max.clone();
  17731. var distance = BABYLON.Vector3.Distance(min, max);
  17732. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17733. this.radius = distance * 0.5;
  17734. this.centerWorld = BABYLON.Vector3.Zero();
  17735. this._update(BABYLON.Matrix.Identity());
  17736. };
  17737. // Methods
  17738. BoundingSphere.prototype._update = function (world) {
  17739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17742. };
  17743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17744. for (var i = 0; i < 6; i++) {
  17745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17746. return false;
  17747. }
  17748. return true;
  17749. };
  17750. BoundingSphere.prototype.intersectsPoint = function (point) {
  17751. var x = this.centerWorld.x - point.x;
  17752. var y = this.centerWorld.y - point.y;
  17753. var z = this.centerWorld.z - point.z;
  17754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17756. return false;
  17757. return true;
  17758. };
  17759. // Statics
  17760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17766. return false;
  17767. return true;
  17768. };
  17769. return BoundingSphere;
  17770. }());
  17771. BABYLON.BoundingSphere = BoundingSphere;
  17772. })(BABYLON || (BABYLON = {}));
  17773. //# sourceMappingURL=babylon.boundingSphere.js.map
  17774. var BABYLON;
  17775. (function (BABYLON) {
  17776. var BoundingBox = /** @class */ (function () {
  17777. /**
  17778. * Creates a new bounding box
  17779. * @param min defines the minimum vector (in local space)
  17780. * @param max defines the maximum vector (in local space)
  17781. */
  17782. function BoundingBox(min, max) {
  17783. this.vectorsWorld = new Array();
  17784. this.reConstruct(min, max);
  17785. }
  17786. // Methods
  17787. /**
  17788. * Recreates the entire bounding box from scratch
  17789. * @param min defines the new minimum vector (in local space)
  17790. * @param max defines the new maximum vector (in local space)
  17791. */
  17792. BoundingBox.prototype.reConstruct = function (min, max) {
  17793. this.minimum = min.clone();
  17794. this.maximum = max.clone();
  17795. // Bounding vectors
  17796. this.vectors = new Array();
  17797. this.vectors.push(this.minimum.clone());
  17798. this.vectors.push(this.maximum.clone());
  17799. this.vectors.push(this.minimum.clone());
  17800. this.vectors[2].x = this.maximum.x;
  17801. this.vectors.push(this.minimum.clone());
  17802. this.vectors[3].y = this.maximum.y;
  17803. this.vectors.push(this.minimum.clone());
  17804. this.vectors[4].z = this.maximum.z;
  17805. this.vectors.push(this.maximum.clone());
  17806. this.vectors[5].z = this.minimum.z;
  17807. this.vectors.push(this.maximum.clone());
  17808. this.vectors[6].x = this.minimum.x;
  17809. this.vectors.push(this.maximum.clone());
  17810. this.vectors[7].y = this.minimum.y;
  17811. // OBB
  17812. this.center = this.maximum.add(this.minimum).scale(0.5);
  17813. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17814. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17815. // World
  17816. for (var index = 0; index < this.vectors.length; index++) {
  17817. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17818. }
  17819. this.minimumWorld = BABYLON.Vector3.Zero();
  17820. this.maximumWorld = BABYLON.Vector3.Zero();
  17821. this.centerWorld = BABYLON.Vector3.Zero();
  17822. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17823. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17824. };
  17825. BoundingBox.prototype.getWorldMatrix = function () {
  17826. return this._worldMatrix;
  17827. };
  17828. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17829. this._worldMatrix.copyFrom(matrix);
  17830. return this;
  17831. };
  17832. BoundingBox.prototype._update = function (world) {
  17833. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17834. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17835. for (var index = 0; index < this.vectors.length; index++) {
  17836. var v = this.vectorsWorld[index];
  17837. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17838. if (v.x < this.minimumWorld.x)
  17839. this.minimumWorld.x = v.x;
  17840. if (v.y < this.minimumWorld.y)
  17841. this.minimumWorld.y = v.y;
  17842. if (v.z < this.minimumWorld.z)
  17843. this.minimumWorld.z = v.z;
  17844. if (v.x > this.maximumWorld.x)
  17845. this.maximumWorld.x = v.x;
  17846. if (v.y > this.maximumWorld.y)
  17847. this.maximumWorld.y = v.y;
  17848. if (v.z > this.maximumWorld.z)
  17849. this.maximumWorld.z = v.z;
  17850. }
  17851. // Extend
  17852. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17853. this.extendSizeWorld.scaleInPlace(0.5);
  17854. // OBB
  17855. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17856. this.centerWorld.scaleInPlace(0.5);
  17857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17858. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17859. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17860. this._worldMatrix = world;
  17861. };
  17862. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17863. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17864. };
  17865. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17866. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17867. };
  17868. BoundingBox.prototype.intersectsPoint = function (point) {
  17869. var delta = -BABYLON.Epsilon;
  17870. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17871. return false;
  17872. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17873. return false;
  17874. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17875. return false;
  17876. return true;
  17877. };
  17878. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17879. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17880. };
  17881. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17882. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17883. return false;
  17884. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17885. return false;
  17886. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17887. return false;
  17888. return true;
  17889. };
  17890. // Statics
  17891. BoundingBox.Intersects = function (box0, box1) {
  17892. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17893. return false;
  17894. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17895. return false;
  17896. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17897. return false;
  17898. return true;
  17899. };
  17900. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17901. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17902. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17903. return (num <= (sphereRadius * sphereRadius));
  17904. };
  17905. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17906. for (var p = 0; p < 6; p++) {
  17907. for (var i = 0; i < 8; i++) {
  17908. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17909. return false;
  17910. }
  17911. }
  17912. }
  17913. return true;
  17914. };
  17915. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17916. for (var p = 0; p < 6; p++) {
  17917. var inCount = 8;
  17918. for (var i = 0; i < 8; i++) {
  17919. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17920. --inCount;
  17921. }
  17922. else {
  17923. break;
  17924. }
  17925. }
  17926. if (inCount === 0)
  17927. return false;
  17928. }
  17929. return true;
  17930. };
  17931. return BoundingBox;
  17932. }());
  17933. BABYLON.BoundingBox = BoundingBox;
  17934. })(BABYLON || (BABYLON = {}));
  17935. //# sourceMappingURL=babylon.boundingBox.js.map
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var computeBoxExtents = function (axis, box) {
  17939. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17940. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17941. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17942. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17943. var r = r0 + r1 + r2;
  17944. return {
  17945. min: p - r,
  17946. max: p + r
  17947. };
  17948. };
  17949. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17950. var axisOverlap = function (axis, box0, box1) {
  17951. var result0 = computeBoxExtents(axis, box0);
  17952. var result1 = computeBoxExtents(axis, box1);
  17953. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17954. };
  17955. var BoundingInfo = /** @class */ (function () {
  17956. function BoundingInfo(minimum, maximum) {
  17957. this.minimum = minimum;
  17958. this.maximum = maximum;
  17959. this._isLocked = false;
  17960. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17961. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17962. }
  17963. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17964. get: function () {
  17965. return this._isLocked;
  17966. },
  17967. set: function (value) {
  17968. this._isLocked = value;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. // Methods
  17974. BoundingInfo.prototype.update = function (world) {
  17975. if (this._isLocked) {
  17976. return;
  17977. }
  17978. this.boundingBox._update(world);
  17979. this.boundingSphere._update(world);
  17980. };
  17981. /**
  17982. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17983. * @param center New center of the bounding info
  17984. * @param extend New extend of the bounding info
  17985. */
  17986. BoundingInfo.prototype.centerOn = function (center, extend) {
  17987. this.minimum = center.subtract(extend);
  17988. this.maximum = center.add(extend);
  17989. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17990. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17991. return this;
  17992. };
  17993. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17994. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17995. return false;
  17996. return this.boundingBox.isInFrustum(frustumPlanes);
  17997. };
  17998. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17999. /**
  18000. * Gets the world distance between the min and max points of the bounding box
  18001. */
  18002. get: function () {
  18003. var boundingBox = this.boundingBox;
  18004. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18005. return size.length();
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18011. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18012. };
  18013. BoundingInfo.prototype._checkCollision = function (collider) {
  18014. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18015. };
  18016. BoundingInfo.prototype.intersectsPoint = function (point) {
  18017. if (!this.boundingSphere.centerWorld) {
  18018. return false;
  18019. }
  18020. if (!this.boundingSphere.intersectsPoint(point)) {
  18021. return false;
  18022. }
  18023. if (!this.boundingBox.intersectsPoint(point)) {
  18024. return false;
  18025. }
  18026. return true;
  18027. };
  18028. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18029. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18030. return false;
  18031. }
  18032. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18033. return false;
  18034. }
  18035. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18036. return false;
  18037. }
  18038. if (!precise) {
  18039. return true;
  18040. }
  18041. var box0 = this.boundingBox;
  18042. var box1 = boundingInfo.boundingBox;
  18043. if (!axisOverlap(box0.directions[0], box0, box1))
  18044. return false;
  18045. if (!axisOverlap(box0.directions[1], box0, box1))
  18046. return false;
  18047. if (!axisOverlap(box0.directions[2], box0, box1))
  18048. return false;
  18049. if (!axisOverlap(box1.directions[0], box0, box1))
  18050. return false;
  18051. if (!axisOverlap(box1.directions[1], box0, box1))
  18052. return false;
  18053. if (!axisOverlap(box1.directions[2], box0, box1))
  18054. return false;
  18055. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18056. return false;
  18057. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18058. return false;
  18059. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18060. return false;
  18061. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18062. return false;
  18063. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18064. return false;
  18065. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18066. return false;
  18067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18068. return false;
  18069. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18070. return false;
  18071. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18072. return false;
  18073. return true;
  18074. };
  18075. return BoundingInfo;
  18076. }());
  18077. BABYLON.BoundingInfo = BoundingInfo;
  18078. })(BABYLON || (BABYLON = {}));
  18079. //# sourceMappingURL=babylon.boundingInfo.js.map
  18080. var BABYLON;
  18081. (function (BABYLON) {
  18082. var TransformNode = /** @class */ (function (_super) {
  18083. __extends(TransformNode, _super);
  18084. function TransformNode(name, scene, isPure) {
  18085. if (scene === void 0) { scene = null; }
  18086. if (isPure === void 0) { isPure = true; }
  18087. var _this = _super.call(this, name, scene) || this;
  18088. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18089. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18090. _this._up = new BABYLON.Vector3(0, 1, 0);
  18091. _this._right = new BABYLON.Vector3(1, 0, 0);
  18092. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18093. // Properties
  18094. _this._rotation = BABYLON.Vector3.Zero();
  18095. _this._scaling = BABYLON.Vector3.One();
  18096. _this._isDirty = false;
  18097. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18098. _this.scalingDeterminant = 1;
  18099. _this.infiniteDistance = false;
  18100. _this.position = BABYLON.Vector3.Zero();
  18101. _this._localWorld = BABYLON.Matrix.Zero();
  18102. _this._worldMatrix = BABYLON.Matrix.Zero();
  18103. _this._worldMatrixDeterminant = 0;
  18104. _this._absolutePosition = BABYLON.Vector3.Zero();
  18105. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18106. _this._postMultiplyPivotMatrix = false;
  18107. _this._isWorldMatrixFrozen = false;
  18108. /**
  18109. * An event triggered after the world matrix is updated
  18110. */
  18111. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18112. _this._nonUniformScaling = false;
  18113. if (isPure) {
  18114. _this.getScene().addTransformNode(_this);
  18115. }
  18116. return _this;
  18117. }
  18118. /**
  18119. * Gets a string idenfifying the name of the class
  18120. * @returns "TransformNode" string
  18121. */
  18122. TransformNode.prototype.getClassName = function () {
  18123. return "TransformNode";
  18124. };
  18125. Object.defineProperty(TransformNode.prototype, "rotation", {
  18126. /**
  18127. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18128. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18129. * Default : (0.0, 0.0, 0.0)
  18130. */
  18131. get: function () {
  18132. return this._rotation;
  18133. },
  18134. set: function (newRotation) {
  18135. this._rotation = newRotation;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Object.defineProperty(TransformNode.prototype, "scaling", {
  18141. /**
  18142. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18143. * Default : (1.0, 1.0, 1.0)
  18144. */
  18145. get: function () {
  18146. return this._scaling;
  18147. },
  18148. /**
  18149. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18150. * Default : (1.0, 1.0, 1.0)
  18151. */
  18152. set: function (newScaling) {
  18153. this._scaling = newScaling;
  18154. },
  18155. enumerable: true,
  18156. configurable: true
  18157. });
  18158. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18159. /**
  18160. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18161. * It's null by default.
  18162. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18163. */
  18164. get: function () {
  18165. return this._rotationQuaternion;
  18166. },
  18167. set: function (quaternion) {
  18168. this._rotationQuaternion = quaternion;
  18169. //reset the rotation vector.
  18170. if (quaternion && this.rotation.length()) {
  18171. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18172. }
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(TransformNode.prototype, "forward", {
  18178. /**
  18179. * The forward direction of that transform in world space.
  18180. */
  18181. get: function () {
  18182. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(TransformNode.prototype, "up", {
  18188. /**
  18189. * The up direction of that transform in world space.
  18190. */
  18191. get: function () {
  18192. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. Object.defineProperty(TransformNode.prototype, "right", {
  18198. /**
  18199. * The right direction of that transform in world space.
  18200. */
  18201. get: function () {
  18202. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. /**
  18208. * Returns the latest update of the World matrix
  18209. * Returns a Matrix.
  18210. */
  18211. TransformNode.prototype.getWorldMatrix = function () {
  18212. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18213. this.computeWorldMatrix();
  18214. }
  18215. return this._worldMatrix;
  18216. };
  18217. /**
  18218. * Returns the latest update of the World matrix determinant.
  18219. */
  18220. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18221. return this._worldMatrixDeterminant;
  18222. };
  18223. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18224. /**
  18225. * Returns directly the latest state of the mesh World matrix.
  18226. * A Matrix is returned.
  18227. */
  18228. get: function () {
  18229. return this._worldMatrix;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. /**
  18235. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18236. * Returns the TransformNode.
  18237. */
  18238. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18239. this._poseMatrix.copyFrom(matrix);
  18240. return this;
  18241. };
  18242. /**
  18243. * Returns the mesh Pose matrix.
  18244. * Returned object : Matrix
  18245. */
  18246. TransformNode.prototype.getPoseMatrix = function () {
  18247. return this._poseMatrix;
  18248. };
  18249. TransformNode.prototype._isSynchronized = function () {
  18250. if (this._isDirty) {
  18251. return false;
  18252. }
  18253. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18254. return false;
  18255. if (this._cache.pivotMatrixUpdated) {
  18256. return false;
  18257. }
  18258. if (this.infiniteDistance) {
  18259. return false;
  18260. }
  18261. if (!this._cache.position.equals(this.position))
  18262. return false;
  18263. if (this.rotationQuaternion) {
  18264. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18265. return false;
  18266. }
  18267. if (!this._cache.rotation.equals(this.rotation))
  18268. return false;
  18269. if (!this._cache.scaling.equals(this.scaling))
  18270. return false;
  18271. return true;
  18272. };
  18273. TransformNode.prototype._initCache = function () {
  18274. _super.prototype._initCache.call(this);
  18275. this._cache.localMatrixUpdated = false;
  18276. this._cache.position = BABYLON.Vector3.Zero();
  18277. this._cache.scaling = BABYLON.Vector3.Zero();
  18278. this._cache.rotation = BABYLON.Vector3.Zero();
  18279. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18280. this._cache.billboardMode = -1;
  18281. };
  18282. TransformNode.prototype.markAsDirty = function (property) {
  18283. if (property === "rotation") {
  18284. this.rotationQuaternion = null;
  18285. }
  18286. this._currentRenderId = Number.MAX_VALUE;
  18287. this._isDirty = true;
  18288. return this;
  18289. };
  18290. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18291. /**
  18292. * Returns the current mesh absolute position.
  18293. * Retuns a Vector3.
  18294. */
  18295. get: function () {
  18296. return this._absolutePosition;
  18297. },
  18298. enumerable: true,
  18299. configurable: true
  18300. });
  18301. /**
  18302. * Sets a new matrix to apply before all other transformation
  18303. * @param matrix defines the transform matrix
  18304. * @returns the current TransformNode
  18305. */
  18306. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18307. return this.setPivotMatrix(matrix, false);
  18308. };
  18309. /**
  18310. * Sets a new pivot matrix to the current node
  18311. * @param matrix defines the new pivot matrix to use
  18312. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18313. * @returns the current TransformNode
  18314. */
  18315. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18316. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18317. this._pivotMatrix = matrix.clone();
  18318. this._cache.pivotMatrixUpdated = true;
  18319. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18320. if (this._postMultiplyPivotMatrix) {
  18321. if (!this._pivotMatrixInverse) {
  18322. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18323. }
  18324. else {
  18325. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18326. }
  18327. }
  18328. return this;
  18329. };
  18330. /**
  18331. * Returns the mesh pivot matrix.
  18332. * Default : Identity.
  18333. * A Matrix is returned.
  18334. */
  18335. TransformNode.prototype.getPivotMatrix = function () {
  18336. return this._pivotMatrix;
  18337. };
  18338. /**
  18339. * Prevents the World matrix to be computed any longer.
  18340. * Returns the TransformNode.
  18341. */
  18342. TransformNode.prototype.freezeWorldMatrix = function () {
  18343. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18344. this.computeWorldMatrix(true);
  18345. this._isWorldMatrixFrozen = true;
  18346. return this;
  18347. };
  18348. /**
  18349. * Allows back the World matrix computation.
  18350. * Returns the TransformNode.
  18351. */
  18352. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18353. this._isWorldMatrixFrozen = false;
  18354. this.computeWorldMatrix(true);
  18355. return this;
  18356. };
  18357. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18358. /**
  18359. * True if the World matrix has been frozen.
  18360. * Returns a boolean.
  18361. */
  18362. get: function () {
  18363. return this._isWorldMatrixFrozen;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. /**
  18369. * Retuns the mesh absolute position in the World.
  18370. * Returns a Vector3.
  18371. */
  18372. TransformNode.prototype.getAbsolutePosition = function () {
  18373. this.computeWorldMatrix();
  18374. return this._absolutePosition;
  18375. };
  18376. /**
  18377. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18378. * Returns the TransformNode.
  18379. */
  18380. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18381. if (!absolutePosition) {
  18382. return this;
  18383. }
  18384. var absolutePositionX;
  18385. var absolutePositionY;
  18386. var absolutePositionZ;
  18387. if (absolutePosition.x === undefined) {
  18388. if (arguments.length < 3) {
  18389. return this;
  18390. }
  18391. absolutePositionX = arguments[0];
  18392. absolutePositionY = arguments[1];
  18393. absolutePositionZ = arguments[2];
  18394. }
  18395. else {
  18396. absolutePositionX = absolutePosition.x;
  18397. absolutePositionY = absolutePosition.y;
  18398. absolutePositionZ = absolutePosition.z;
  18399. }
  18400. if (this.parent) {
  18401. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18402. invertParentWorldMatrix.invert();
  18403. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18404. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18405. }
  18406. else {
  18407. this.position.x = absolutePositionX;
  18408. this.position.y = absolutePositionY;
  18409. this.position.z = absolutePositionZ;
  18410. }
  18411. return this;
  18412. };
  18413. /**
  18414. * Sets the mesh position in its local space.
  18415. * Returns the TransformNode.
  18416. */
  18417. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18418. this.computeWorldMatrix();
  18419. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18420. return this;
  18421. };
  18422. /**
  18423. * Returns the mesh position in the local space from the current World matrix values.
  18424. * Returns a new Vector3.
  18425. */
  18426. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18427. this.computeWorldMatrix();
  18428. var invLocalWorldMatrix = this._localWorld.clone();
  18429. invLocalWorldMatrix.invert();
  18430. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18431. };
  18432. /**
  18433. * Translates the mesh along the passed Vector3 in its local space.
  18434. * Returns the TransformNode.
  18435. */
  18436. TransformNode.prototype.locallyTranslate = function (vector3) {
  18437. this.computeWorldMatrix(true);
  18438. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18439. return this;
  18440. };
  18441. /**
  18442. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18443. * @param targetPoint the position (must be in same space as current mesh) to look at
  18444. * @param yawCor optional yaw (y-axis) correction in radians
  18445. * @param pitchCor optional pitch (x-axis) correction in radians
  18446. * @param rollCor optional roll (z-axis) correction in radians
  18447. * @param space the choosen space of the target
  18448. * @returns the TransformNode.
  18449. */
  18450. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18451. if (yawCor === void 0) { yawCor = 0; }
  18452. if (pitchCor === void 0) { pitchCor = 0; }
  18453. if (rollCor === void 0) { rollCor = 0; }
  18454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18455. var dv = TransformNode._lookAtVectorCache;
  18456. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18457. targetPoint.subtractToRef(pos, dv);
  18458. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18459. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18460. var pitch = Math.atan2(dv.y, len);
  18461. if (this.rotationQuaternion) {
  18462. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18463. }
  18464. else {
  18465. this.rotation.x = pitch + pitchCor;
  18466. this.rotation.y = yaw + yawCor;
  18467. this.rotation.z = rollCor;
  18468. }
  18469. return this;
  18470. };
  18471. /**
  18472. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18473. * This Vector3 is expressed in the World space.
  18474. */
  18475. TransformNode.prototype.getDirection = function (localAxis) {
  18476. var result = BABYLON.Vector3.Zero();
  18477. this.getDirectionToRef(localAxis, result);
  18478. return result;
  18479. };
  18480. /**
  18481. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18482. * localAxis is expressed in the mesh local space.
  18483. * result is computed in the Wordl space from the mesh World matrix.
  18484. * Returns the TransformNode.
  18485. */
  18486. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18487. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18488. return this;
  18489. };
  18490. /**
  18491. * Sets a new pivot point to the current node
  18492. * @param point defines the new pivot point to use
  18493. * @param space defines if the point is in world or local space (local by default)
  18494. * @returns the current TransformNode
  18495. */
  18496. TransformNode.prototype.setPivotPoint = function (point, space) {
  18497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18498. if (this.getScene().getRenderId() == 0) {
  18499. this.computeWorldMatrix(true);
  18500. }
  18501. var wm = this.getWorldMatrix();
  18502. if (space == BABYLON.Space.WORLD) {
  18503. var tmat = BABYLON.Tmp.Matrix[0];
  18504. wm.invertToRef(tmat);
  18505. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18506. }
  18507. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18508. };
  18509. /**
  18510. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18511. */
  18512. TransformNode.prototype.getPivotPoint = function () {
  18513. var point = BABYLON.Vector3.Zero();
  18514. this.getPivotPointToRef(point);
  18515. return point;
  18516. };
  18517. /**
  18518. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18519. * Returns the TransformNode.
  18520. */
  18521. TransformNode.prototype.getPivotPointToRef = function (result) {
  18522. result.x = -this._pivotMatrix.m[12];
  18523. result.y = -this._pivotMatrix.m[13];
  18524. result.z = -this._pivotMatrix.m[14];
  18525. return this;
  18526. };
  18527. /**
  18528. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18529. */
  18530. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18531. var point = BABYLON.Vector3.Zero();
  18532. this.getAbsolutePivotPointToRef(point);
  18533. return point;
  18534. };
  18535. /**
  18536. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18537. * Returns the TransformNode.
  18538. */
  18539. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18540. result.x = this._pivotMatrix.m[12];
  18541. result.y = this._pivotMatrix.m[13];
  18542. result.z = this._pivotMatrix.m[14];
  18543. this.getPivotPointToRef(result);
  18544. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18545. return this;
  18546. };
  18547. /**
  18548. * Defines the passed node as the parent of the current node.
  18549. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18550. * Returns the TransformNode.
  18551. */
  18552. TransformNode.prototype.setParent = function (node) {
  18553. if (node === null) {
  18554. var rotation = BABYLON.Tmp.Quaternion[0];
  18555. var position = BABYLON.Tmp.Vector3[0];
  18556. var scale = BABYLON.Tmp.Vector3[1];
  18557. if (this.parent && this.parent.computeWorldMatrix) {
  18558. this.parent.computeWorldMatrix(true);
  18559. }
  18560. this.computeWorldMatrix(true);
  18561. this.getWorldMatrix().decompose(scale, rotation, position);
  18562. if (this.rotationQuaternion) {
  18563. this.rotationQuaternion.copyFrom(rotation);
  18564. }
  18565. else {
  18566. rotation.toEulerAnglesToRef(this.rotation);
  18567. }
  18568. this.scaling.x = scale.x;
  18569. this.scaling.y = scale.y;
  18570. this.scaling.z = scale.z;
  18571. this.position.x = position.x;
  18572. this.position.y = position.y;
  18573. this.position.z = position.z;
  18574. }
  18575. else {
  18576. var rotation = BABYLON.Tmp.Quaternion[0];
  18577. var position = BABYLON.Tmp.Vector3[0];
  18578. var scale = BABYLON.Tmp.Vector3[1];
  18579. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18580. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18581. this.computeWorldMatrix(true);
  18582. node.computeWorldMatrix(true);
  18583. node.getWorldMatrix().invertToRef(invParentMatrix);
  18584. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18585. diffMatrix.decompose(scale, rotation, position);
  18586. if (this.rotationQuaternion) {
  18587. this.rotationQuaternion.copyFrom(rotation);
  18588. }
  18589. else {
  18590. rotation.toEulerAnglesToRef(this.rotation);
  18591. }
  18592. this.position.x = position.x;
  18593. this.position.y = position.y;
  18594. this.position.z = position.z;
  18595. this.scaling.x = scale.x;
  18596. this.scaling.y = scale.y;
  18597. this.scaling.z = scale.z;
  18598. }
  18599. this.parent = node;
  18600. return this;
  18601. };
  18602. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18603. get: function () {
  18604. return this._nonUniformScaling;
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18610. if (this._nonUniformScaling === value) {
  18611. return false;
  18612. }
  18613. this._nonUniformScaling = true;
  18614. return true;
  18615. };
  18616. /**
  18617. * Attach the current TransformNode to another TransformNode associated with a bone
  18618. * @param bone Bone affecting the TransformNode
  18619. * @param affectedTransformNode TransformNode associated with the bone
  18620. */
  18621. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18622. this._transformToBoneReferal = affectedTransformNode;
  18623. this.parent = bone;
  18624. if (bone.getWorldMatrix().determinant() < 0) {
  18625. this.scalingDeterminant *= -1;
  18626. }
  18627. return this;
  18628. };
  18629. TransformNode.prototype.detachFromBone = function () {
  18630. if (!this.parent) {
  18631. return this;
  18632. }
  18633. if (this.parent.getWorldMatrix().determinant() < 0) {
  18634. this.scalingDeterminant *= -1;
  18635. }
  18636. this._transformToBoneReferal = null;
  18637. this.parent = null;
  18638. return this;
  18639. };
  18640. /**
  18641. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18642. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18643. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18644. * The passed axis is also normalized.
  18645. * Returns the TransformNode.
  18646. */
  18647. TransformNode.prototype.rotate = function (axis, amount, space) {
  18648. axis.normalize();
  18649. if (!this.rotationQuaternion) {
  18650. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18651. this.rotation = BABYLON.Vector3.Zero();
  18652. }
  18653. var rotationQuaternion;
  18654. if (!space || space === BABYLON.Space.LOCAL) {
  18655. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18656. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18657. }
  18658. else {
  18659. if (this.parent) {
  18660. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18661. invertParentWorldMatrix.invert();
  18662. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18663. }
  18664. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18665. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18666. }
  18667. return this;
  18668. };
  18669. /**
  18670. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18671. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18672. * The passed axis is also normalized.
  18673. * Returns the TransformNode.
  18674. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18675. */
  18676. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18677. axis.normalize();
  18678. if (!this.rotationQuaternion) {
  18679. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18680. this.rotation.copyFromFloats(0, 0, 0);
  18681. }
  18682. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18683. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18684. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18685. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18686. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18687. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18688. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18689. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18690. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18691. return this;
  18692. };
  18693. /**
  18694. * Translates the mesh along the axis vector for the passed distance in the given space.
  18695. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18696. * Returns the TransformNode.
  18697. */
  18698. TransformNode.prototype.translate = function (axis, distance, space) {
  18699. var displacementVector = axis.scale(distance);
  18700. if (!space || space === BABYLON.Space.LOCAL) {
  18701. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18702. this.setPositionWithLocalVector(tempV3);
  18703. }
  18704. else {
  18705. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18706. }
  18707. return this;
  18708. };
  18709. /**
  18710. * Adds a rotation step to the mesh current rotation.
  18711. * x, y, z are Euler angles expressed in radians.
  18712. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18713. * This means this rotation is made in the mesh local space only.
  18714. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18715. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18716. * ```javascript
  18717. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18718. * ```
  18719. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18720. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  18721. * Returns the TransformNode.
  18722. */
  18723. TransformNode.prototype.addRotation = function (x, y, z) {
  18724. var rotationQuaternion;
  18725. if (this.rotationQuaternion) {
  18726. rotationQuaternion = this.rotationQuaternion;
  18727. }
  18728. else {
  18729. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18730. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18731. }
  18732. var accumulation = BABYLON.Tmp.Quaternion[0];
  18733. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18734. rotationQuaternion.multiplyInPlace(accumulation);
  18735. if (!this.rotationQuaternion) {
  18736. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18737. }
  18738. return this;
  18739. };
  18740. /**
  18741. * Computes the mesh World matrix and returns it.
  18742. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18743. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18744. * If the parameter `force`is set to `true`, the actual computation is done.
  18745. * Returns the mesh World Matrix.
  18746. */
  18747. TransformNode.prototype.computeWorldMatrix = function (force) {
  18748. if (this._isWorldMatrixFrozen) {
  18749. return this._worldMatrix;
  18750. }
  18751. if (!force && this.isSynchronized(true)) {
  18752. this._currentRenderId = this.getScene().getRenderId();
  18753. return this._worldMatrix;
  18754. }
  18755. this._cache.position.copyFrom(this.position);
  18756. this._cache.scaling.copyFrom(this.scaling);
  18757. this._cache.pivotMatrixUpdated = false;
  18758. this._cache.billboardMode = this.billboardMode;
  18759. this._currentRenderId = this.getScene().getRenderId();
  18760. this._childRenderId = this.getScene().getRenderId();
  18761. this._isDirty = false;
  18762. // Scaling
  18763. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18764. // Rotation
  18765. //rotate, if quaternion is set and rotation was used
  18766. if (this.rotationQuaternion) {
  18767. var len = this.rotation.length();
  18768. if (len) {
  18769. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18770. this.rotation.copyFromFloats(0, 0, 0);
  18771. }
  18772. }
  18773. if (this.rotationQuaternion) {
  18774. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18775. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18776. }
  18777. else {
  18778. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18779. this._cache.rotation.copyFrom(this.rotation);
  18780. }
  18781. // Translation
  18782. var camera = this.getScene().activeCamera;
  18783. if (this.infiniteDistance && !this.parent && camera) {
  18784. var cameraWorldMatrix = camera.getWorldMatrix();
  18785. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18786. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18787. }
  18788. else {
  18789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18790. }
  18791. // Composing transformations
  18792. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18793. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18794. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18795. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18796. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18797. // Need to decompose each rotation here
  18798. var currentPosition = BABYLON.Tmp.Vector3[3];
  18799. if (this.parent && this.parent.getWorldMatrix) {
  18800. if (this._transformToBoneReferal) {
  18801. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18802. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18803. }
  18804. else {
  18805. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18806. }
  18807. }
  18808. else {
  18809. currentPosition.copyFrom(this.position);
  18810. }
  18811. currentPosition.subtractInPlace(camera.globalPosition);
  18812. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18813. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18814. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18815. }
  18816. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18817. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18818. }
  18819. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18820. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18821. }
  18822. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18823. }
  18824. else {
  18825. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18826. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18827. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18828. }
  18829. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18830. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18831. }
  18832. // Local world
  18833. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18834. // Parent
  18835. if (this.parent && this.parent.getWorldMatrix) {
  18836. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18837. if (this._transformToBoneReferal) {
  18838. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18839. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18840. }
  18841. else {
  18842. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18843. }
  18844. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18845. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18846. this._worldMatrix.copyFrom(this._localWorld);
  18847. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18848. }
  18849. else {
  18850. if (this._transformToBoneReferal) {
  18851. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18852. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18853. }
  18854. else {
  18855. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18856. }
  18857. }
  18858. this._markSyncedWithParent();
  18859. }
  18860. else {
  18861. this._worldMatrix.copyFrom(this._localWorld);
  18862. }
  18863. // Post multiply inverse of pivotMatrix
  18864. if (this._postMultiplyPivotMatrix) {
  18865. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18866. }
  18867. // Normal matrix
  18868. if (this.scaling.isNonUniform) {
  18869. this._updateNonUniformScalingState(true);
  18870. }
  18871. else if (this.parent && this.parent._nonUniformScaling) {
  18872. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18873. }
  18874. else {
  18875. this._updateNonUniformScalingState(false);
  18876. }
  18877. this._afterComputeWorldMatrix();
  18878. // Absolute position
  18879. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18880. // Callbacks
  18881. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18882. if (!this._poseMatrix) {
  18883. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18884. }
  18885. // Cache the determinant
  18886. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18887. return this._worldMatrix;
  18888. };
  18889. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18890. };
  18891. /**
  18892. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18893. * @param func: callback function to add
  18894. *
  18895. * Returns the TransformNode.
  18896. */
  18897. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18898. this.onAfterWorldMatrixUpdateObservable.add(func);
  18899. return this;
  18900. };
  18901. /**
  18902. * Removes a registered callback function.
  18903. * Returns the TransformNode.
  18904. */
  18905. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18906. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18907. return this;
  18908. };
  18909. /**
  18910. * Clone the current transform node
  18911. * Returns the new transform node
  18912. * @param name Name of the new clone
  18913. * @param newParent New parent for the clone
  18914. * @param doNotCloneChildren Do not clone children hierarchy
  18915. */
  18916. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18917. var _this = this;
  18918. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18919. result.name = name;
  18920. result.id = name;
  18921. if (newParent) {
  18922. result.parent = newParent;
  18923. }
  18924. if (!doNotCloneChildren) {
  18925. // Children
  18926. var directDescendants = this.getDescendants(true);
  18927. for (var index = 0; index < directDescendants.length; index++) {
  18928. var child = directDescendants[index];
  18929. if (child.clone) {
  18930. child.clone(name + "." + child.name, result);
  18931. }
  18932. }
  18933. }
  18934. return result;
  18935. };
  18936. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18937. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18938. serializationObject.type = this.getClassName();
  18939. // Parent
  18940. if (this.parent) {
  18941. serializationObject.parentId = this.parent.id;
  18942. }
  18943. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18944. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18945. }
  18946. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18947. serializationObject.isEnabled = this.isEnabled();
  18948. // Parent
  18949. if (this.parent) {
  18950. serializationObject.parentId = this.parent.id;
  18951. }
  18952. return serializationObject;
  18953. };
  18954. // Statics
  18955. /**
  18956. * Returns a new TransformNode object parsed from the source provided.
  18957. * The parameter `parsedMesh` is the source.
  18958. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18959. */
  18960. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18961. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18962. if (BABYLON.Tags) {
  18963. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18964. }
  18965. if (parsedTransformNode.localMatrix) {
  18966. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18967. }
  18968. else if (parsedTransformNode.pivotMatrix) {
  18969. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18970. }
  18971. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18972. // Parent
  18973. if (parsedTransformNode.parentId) {
  18974. transformNode._waitingParentId = parsedTransformNode.parentId;
  18975. }
  18976. return transformNode;
  18977. };
  18978. /**
  18979. * Releases resources associated with this transform node.
  18980. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18981. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18982. */
  18983. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18984. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18985. // Animations
  18986. this.getScene().stopAnimation(this);
  18987. // Remove from scene
  18988. this.getScene().removeTransformNode(this);
  18989. this.onAfterWorldMatrixUpdateObservable.clear();
  18990. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18991. };
  18992. // Statics
  18993. TransformNode.BILLBOARDMODE_NONE = 0;
  18994. TransformNode.BILLBOARDMODE_X = 1;
  18995. TransformNode.BILLBOARDMODE_Y = 2;
  18996. TransformNode.BILLBOARDMODE_Z = 4;
  18997. TransformNode.BILLBOARDMODE_ALL = 7;
  18998. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18999. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19000. __decorate([
  19001. BABYLON.serializeAsVector3()
  19002. ], TransformNode.prototype, "_rotation", void 0);
  19003. __decorate([
  19004. BABYLON.serializeAsQuaternion()
  19005. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19006. __decorate([
  19007. BABYLON.serializeAsVector3()
  19008. ], TransformNode.prototype, "_scaling", void 0);
  19009. __decorate([
  19010. BABYLON.serialize()
  19011. ], TransformNode.prototype, "billboardMode", void 0);
  19012. __decorate([
  19013. BABYLON.serialize()
  19014. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19015. __decorate([
  19016. BABYLON.serialize()
  19017. ], TransformNode.prototype, "infiniteDistance", void 0);
  19018. __decorate([
  19019. BABYLON.serializeAsVector3()
  19020. ], TransformNode.prototype, "position", void 0);
  19021. return TransformNode;
  19022. }(BABYLON.Node));
  19023. BABYLON.TransformNode = TransformNode;
  19024. })(BABYLON || (BABYLON = {}));
  19025. //# sourceMappingURL=babylon.transformNode.js.map
  19026. var BABYLON;
  19027. (function (BABYLON) {
  19028. var AbstractMesh = /** @class */ (function (_super) {
  19029. __extends(AbstractMesh, _super);
  19030. // Constructor
  19031. function AbstractMesh(name, scene) {
  19032. if (scene === void 0) { scene = null; }
  19033. var _this = _super.call(this, name, scene, false) || this;
  19034. _this._facetNb = 0; // facet number
  19035. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19036. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19037. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19038. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19039. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19040. _this._subDiv = {
  19041. max: 1,
  19042. X: 1,
  19043. Y: 1,
  19044. Z: 1
  19045. };
  19046. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19047. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19048. // Events
  19049. /**
  19050. * An event triggered when this mesh collides with another one
  19051. */
  19052. _this.onCollideObservable = new BABYLON.Observable();
  19053. /**
  19054. * An event triggered when the collision's position changes
  19055. */
  19056. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19057. /**
  19058. * An event triggered when material is changed
  19059. */
  19060. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19061. // Properties
  19062. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19063. /**
  19064. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19065. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19066. * or
  19067. * 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.
  19068. * for more info check WebGl documentations
  19069. */
  19070. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19071. /**
  19072. * 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:
  19073. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19074. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19075. * 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.
  19076. */
  19077. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19078. /**
  19079. * 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.
  19080. * The default value is -1 which means don't break the query and wait till the result.
  19081. */
  19082. _this.occlusionRetryCount = -1;
  19083. _this._occlusionInternalRetryCounter = 0;
  19084. _this._isOccluded = false;
  19085. _this._isOcclusionQueryInProgress = false;
  19086. _this._visibility = 1.0;
  19087. _this.alphaIndex = Number.MAX_VALUE;
  19088. _this.isVisible = true;
  19089. _this.isPickable = true;
  19090. _this.showBoundingBox = false;
  19091. _this.showSubMeshesBoundingBox = false;
  19092. _this.isBlocker = false;
  19093. _this.enablePointerMoveEvents = false;
  19094. _this.renderingGroupId = 0;
  19095. _this._receiveShadows = false;
  19096. _this.renderOutline = false;
  19097. _this.outlineColor = BABYLON.Color3.Red();
  19098. _this.outlineWidth = 0.02;
  19099. _this.renderOverlay = false;
  19100. _this.overlayColor = BABYLON.Color3.Red();
  19101. _this.overlayAlpha = 0.5;
  19102. _this._hasVertexAlpha = false;
  19103. _this._useVertexColors = true;
  19104. _this._computeBonesUsingShaders = true;
  19105. _this._numBoneInfluencers = 4;
  19106. _this._applyFog = true;
  19107. _this.useOctreeForRenderingSelection = true;
  19108. _this.useOctreeForPicking = true;
  19109. _this.useOctreeForCollisions = true;
  19110. _this._layerMask = 0x0FFFFFFF;
  19111. /**
  19112. * True if the mesh must be rendered in any case.
  19113. */
  19114. _this.alwaysSelectAsActiveMesh = false;
  19115. /**
  19116. * This scene's action manager
  19117. */
  19118. _this.actionManager = null;
  19119. // Physics
  19120. _this.physicsImpostor = null;
  19121. // Collisions
  19122. _this._checkCollisions = false;
  19123. _this._collisionMask = -1;
  19124. _this._collisionGroup = -1;
  19125. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19126. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19127. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19128. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19129. // Edges
  19130. _this.edgesWidth = 1;
  19131. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19132. // Cache
  19133. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19134. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19135. _this._renderId = 0;
  19136. _this._intersectionsInProgress = new Array();
  19137. _this._unIndexed = false;
  19138. _this._lightSources = new Array();
  19139. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19140. if (collidedMesh === void 0) { collidedMesh = null; }
  19141. //TODO move this to the collision coordinator!
  19142. if (_this.getScene().workerCollisions)
  19143. newPosition.multiplyInPlace(_this._collider._radius);
  19144. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19145. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19146. _this.position.addInPlace(_this._diffPositionForCollisions);
  19147. }
  19148. if (collidedMesh) {
  19149. _this.onCollideObservable.notifyObservers(collidedMesh);
  19150. }
  19151. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19152. };
  19153. _this.getScene().addMesh(_this);
  19154. _this._resyncLightSources();
  19155. return _this;
  19156. }
  19157. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19158. get: function () {
  19159. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19160. },
  19161. enumerable: true,
  19162. configurable: true
  19163. });
  19164. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19165. get: function () {
  19166. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19167. },
  19168. enumerable: true,
  19169. configurable: true
  19170. });
  19171. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19172. get: function () {
  19173. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19179. get: function () {
  19180. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19181. },
  19182. enumerable: true,
  19183. configurable: true
  19184. });
  19185. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19186. get: function () {
  19187. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19193. /**
  19194. * Read-only : the number of facets in the mesh
  19195. */
  19196. get: function () {
  19197. return this._facetNb;
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19203. /**
  19204. * The number (integer) of subdivisions per axis in the partioning space
  19205. */
  19206. get: function () {
  19207. return this._partitioningSubdivisions;
  19208. },
  19209. set: function (nb) {
  19210. this._partitioningSubdivisions = nb;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19216. /**
  19217. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19218. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19219. */
  19220. get: function () {
  19221. return this._partitioningBBoxRatio;
  19222. },
  19223. set: function (ratio) {
  19224. this._partitioningBBoxRatio = ratio;
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19230. /**
  19231. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19232. * Works only for updatable meshes.
  19233. * Doesn't work with multi-materials.
  19234. */
  19235. get: function () {
  19236. return this._facetDepthSort;
  19237. },
  19238. set: function (sort) {
  19239. this._facetDepthSort = sort;
  19240. },
  19241. enumerable: true,
  19242. configurable: true
  19243. });
  19244. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19245. /**
  19246. * The location (Vector3) where the facet depth sort must be computed from.
  19247. * By default, the active camera position.
  19248. * Used only when facet depth sort is enabled.
  19249. */
  19250. get: function () {
  19251. return this._facetDepthSortFrom;
  19252. },
  19253. set: function (location) {
  19254. this._facetDepthSortFrom = location;
  19255. },
  19256. enumerable: true,
  19257. configurable: true
  19258. });
  19259. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19260. /**
  19261. * Read-only boolean : is the feature facetData enabled ?
  19262. */
  19263. get: function () {
  19264. return this._facetDataEnabled;
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19270. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19271. return false;
  19272. }
  19273. this._markSubMeshesAsMiscDirty();
  19274. return true;
  19275. };
  19276. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19277. set: function (callback) {
  19278. if (this._onCollideObserver) {
  19279. this.onCollideObservable.remove(this._onCollideObserver);
  19280. }
  19281. this._onCollideObserver = this.onCollideObservable.add(callback);
  19282. },
  19283. enumerable: true,
  19284. configurable: true
  19285. });
  19286. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19287. set: function (callback) {
  19288. if (this._onCollisionPositionChangeObserver) {
  19289. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19290. }
  19291. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19297. /**
  19298. * 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.
  19299. */
  19300. get: function () {
  19301. return this._isOccluded;
  19302. },
  19303. set: function (value) {
  19304. this._isOccluded = value;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19310. /**
  19311. * Flag to check the progress status of the query
  19312. */
  19313. get: function () {
  19314. return this._isOcclusionQueryInProgress;
  19315. },
  19316. enumerable: true,
  19317. configurable: true
  19318. });
  19319. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19320. /**
  19321. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19322. */
  19323. get: function () {
  19324. return this._visibility;
  19325. },
  19326. /**
  19327. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19328. */
  19329. set: function (value) {
  19330. if (this._visibility === value) {
  19331. return;
  19332. }
  19333. this._visibility = value;
  19334. this._markSubMeshesAsMiscDirty();
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(AbstractMesh.prototype, "material", {
  19340. get: function () {
  19341. return this._material;
  19342. },
  19343. set: function (value) {
  19344. if (this._material === value) {
  19345. return;
  19346. }
  19347. this._material = value;
  19348. if (this.onMaterialChangedObservable.hasObservers) {
  19349. this.onMaterialChangedObservable.notifyObservers(this);
  19350. }
  19351. if (!this.subMeshes) {
  19352. return;
  19353. }
  19354. this._unBindEffect();
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19360. get: function () {
  19361. return this._receiveShadows;
  19362. },
  19363. set: function (value) {
  19364. if (this._receiveShadows === value) {
  19365. return;
  19366. }
  19367. this._receiveShadows = value;
  19368. this._markSubMeshesAsLightDirty();
  19369. },
  19370. enumerable: true,
  19371. configurable: true
  19372. });
  19373. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19374. get: function () {
  19375. return this._hasVertexAlpha;
  19376. },
  19377. set: function (value) {
  19378. if (this._hasVertexAlpha === value) {
  19379. return;
  19380. }
  19381. this._hasVertexAlpha = value;
  19382. this._markSubMeshesAsAttributesDirty();
  19383. this._markSubMeshesAsMiscDirty();
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19389. get: function () {
  19390. return this._useVertexColors;
  19391. },
  19392. set: function (value) {
  19393. if (this._useVertexColors === value) {
  19394. return;
  19395. }
  19396. this._useVertexColors = value;
  19397. this._markSubMeshesAsAttributesDirty();
  19398. },
  19399. enumerable: true,
  19400. configurable: true
  19401. });
  19402. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19403. get: function () {
  19404. return this._computeBonesUsingShaders;
  19405. },
  19406. set: function (value) {
  19407. if (this._computeBonesUsingShaders === value) {
  19408. return;
  19409. }
  19410. this._computeBonesUsingShaders = value;
  19411. this._markSubMeshesAsAttributesDirty();
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19417. get: function () {
  19418. return this._numBoneInfluencers;
  19419. },
  19420. set: function (value) {
  19421. if (this._numBoneInfluencers === value) {
  19422. return;
  19423. }
  19424. this._numBoneInfluencers = value;
  19425. this._markSubMeshesAsAttributesDirty();
  19426. },
  19427. enumerable: true,
  19428. configurable: true
  19429. });
  19430. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19431. get: function () {
  19432. return this._applyFog;
  19433. },
  19434. set: function (value) {
  19435. if (this._applyFog === value) {
  19436. return;
  19437. }
  19438. this._applyFog = value;
  19439. this._markSubMeshesAsMiscDirty();
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19445. get: function () {
  19446. return this._layerMask;
  19447. },
  19448. set: function (value) {
  19449. if (value === this._layerMask) {
  19450. return;
  19451. }
  19452. this._layerMask = value;
  19453. this._resyncLightSources();
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19459. get: function () {
  19460. return this._collisionMask;
  19461. },
  19462. set: function (mask) {
  19463. this._collisionMask = !isNaN(mask) ? mask : -1;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19469. get: function () {
  19470. return this._collisionGroup;
  19471. },
  19472. set: function (mask) {
  19473. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19479. get: function () {
  19480. return null;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19486. get: function () {
  19487. return this._skeleton;
  19488. },
  19489. set: function (value) {
  19490. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19491. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19492. }
  19493. if (value && value.needInitialSkinMatrix) {
  19494. value._registerMeshWithPoseMatrix(this);
  19495. }
  19496. this._skeleton = value;
  19497. if (!this._skeleton) {
  19498. this._bonesTransformMatrices = null;
  19499. }
  19500. this._markSubMeshesAsAttributesDirty();
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. /**
  19506. * Returns the string "AbstractMesh"
  19507. */
  19508. AbstractMesh.prototype.getClassName = function () {
  19509. return "AbstractMesh";
  19510. };
  19511. /**
  19512. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19513. */
  19514. AbstractMesh.prototype.toString = function (fullDetails) {
  19515. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19516. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19517. if (this._skeleton) {
  19518. ret += ", skeleton: " + this._skeleton.name;
  19519. }
  19520. if (fullDetails) {
  19521. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19522. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19523. }
  19524. return ret;
  19525. };
  19526. AbstractMesh.prototype._rebuild = function () {
  19527. if (this._occlusionQuery) {
  19528. this._occlusionQuery = null;
  19529. }
  19530. if (this._edgesRenderer) {
  19531. this._edgesRenderer._rebuild();
  19532. }
  19533. if (!this.subMeshes) {
  19534. return;
  19535. }
  19536. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19537. var subMesh = _a[_i];
  19538. subMesh._rebuild();
  19539. }
  19540. };
  19541. AbstractMesh.prototype._resyncLightSources = function () {
  19542. this._lightSources.length = 0;
  19543. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19544. var light = _a[_i];
  19545. if (!light.isEnabled()) {
  19546. continue;
  19547. }
  19548. if (light.canAffectMesh(this)) {
  19549. this._lightSources.push(light);
  19550. }
  19551. }
  19552. this._markSubMeshesAsLightDirty();
  19553. };
  19554. AbstractMesh.prototype._resyncLighSource = function (light) {
  19555. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19556. var index = this._lightSources.indexOf(light);
  19557. if (index === -1) {
  19558. if (!isIn) {
  19559. return;
  19560. }
  19561. this._lightSources.push(light);
  19562. }
  19563. else {
  19564. if (isIn) {
  19565. return;
  19566. }
  19567. this._lightSources.splice(index, 1);
  19568. }
  19569. this._markSubMeshesAsLightDirty();
  19570. };
  19571. /** @ignore */
  19572. AbstractMesh.prototype._unBindEffect = function () {
  19573. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19574. var subMesh = _a[_i];
  19575. subMesh.setEffect(null);
  19576. }
  19577. };
  19578. AbstractMesh.prototype._removeLightSource = function (light) {
  19579. var index = this._lightSources.indexOf(light);
  19580. if (index === -1) {
  19581. return;
  19582. }
  19583. this._lightSources.splice(index, 1);
  19584. this._markSubMeshesAsLightDirty();
  19585. };
  19586. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19587. if (!this.subMeshes) {
  19588. return;
  19589. }
  19590. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19591. var subMesh = _a[_i];
  19592. if (subMesh._materialDefines) {
  19593. func(subMesh._materialDefines);
  19594. }
  19595. }
  19596. };
  19597. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19598. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19599. };
  19600. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19601. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19602. };
  19603. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19604. if (!this.subMeshes) {
  19605. return;
  19606. }
  19607. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19608. var subMesh = _a[_i];
  19609. var material = subMesh.getMaterial();
  19610. if (material) {
  19611. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19612. }
  19613. }
  19614. };
  19615. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19616. /**
  19617. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19618. * Default : (1.0, 1.0, 1.0)
  19619. */
  19620. get: function () {
  19621. return this._scaling;
  19622. },
  19623. /**
  19624. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19625. * Default : (1.0, 1.0, 1.0)
  19626. */
  19627. set: function (newScaling) {
  19628. this._scaling = newScaling;
  19629. if (this.physicsImpostor) {
  19630. this.physicsImpostor.forceUpdate();
  19631. }
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. // Methods
  19637. /**
  19638. * Disables the mesh edger rendering mode.
  19639. * Returns the AbstractMesh.
  19640. */
  19641. AbstractMesh.prototype.disableEdgesRendering = function () {
  19642. if (this._edgesRenderer) {
  19643. this._edgesRenderer.dispose();
  19644. this._edgesRenderer = null;
  19645. }
  19646. return this;
  19647. };
  19648. /**
  19649. * Enables the edge rendering mode on the mesh.
  19650. * This mode makes the mesh edges visible.
  19651. * Returns the AbstractMesh.
  19652. */
  19653. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19654. if (epsilon === void 0) { epsilon = 0.95; }
  19655. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19656. this.disableEdgesRendering();
  19657. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19658. return this;
  19659. };
  19660. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19661. /**
  19662. * Returns true if the mesh is blocked. Used by the class Mesh.
  19663. * Returns the boolean `false` by default.
  19664. */
  19665. get: function () {
  19666. return false;
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. /**
  19672. * Returns the mesh itself by default, used by the class Mesh.
  19673. * Returned type : AbstractMesh
  19674. */
  19675. AbstractMesh.prototype.getLOD = function (camera) {
  19676. return this;
  19677. };
  19678. /**
  19679. * Returns 0 by default, used by the class Mesh.
  19680. * Returns an integer.
  19681. */
  19682. AbstractMesh.prototype.getTotalVertices = function () {
  19683. return 0;
  19684. };
  19685. /**
  19686. * Returns null by default, used by the class Mesh.
  19687. * Returned type : integer array
  19688. */
  19689. AbstractMesh.prototype.getIndices = function () {
  19690. return null;
  19691. };
  19692. /**
  19693. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19694. * Returned type : float array or Float32Array
  19695. */
  19696. AbstractMesh.prototype.getVerticesData = function (kind) {
  19697. return null;
  19698. };
  19699. /**
  19700. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19701. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19702. * The `data` are either a numeric array either a Float32Array.
  19703. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19704. * 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).
  19705. * Note that a new underlying VertexBuffer object is created each call.
  19706. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19707. *
  19708. * Possible `kind` values :
  19709. * - BABYLON.VertexBuffer.PositionKind
  19710. * - BABYLON.VertexBuffer.UVKind
  19711. * - BABYLON.VertexBuffer.UV2Kind
  19712. * - BABYLON.VertexBuffer.UV3Kind
  19713. * - BABYLON.VertexBuffer.UV4Kind
  19714. * - BABYLON.VertexBuffer.UV5Kind
  19715. * - BABYLON.VertexBuffer.UV6Kind
  19716. * - BABYLON.VertexBuffer.ColorKind
  19717. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19718. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19719. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19720. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19721. *
  19722. * Returns the Mesh.
  19723. */
  19724. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19725. return this;
  19726. };
  19727. /**
  19728. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19729. * If the mesh has no geometry, it is simply returned as it is.
  19730. * The `data` are either a numeric array either a Float32Array.
  19731. * No new underlying VertexBuffer object is created.
  19732. * 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.
  19733. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19734. *
  19735. * Possible `kind` values :
  19736. * - BABYLON.VertexBuffer.PositionKind
  19737. * - BABYLON.VertexBuffer.UVKind
  19738. * - BABYLON.VertexBuffer.UV2Kind
  19739. * - BABYLON.VertexBuffer.UV3Kind
  19740. * - BABYLON.VertexBuffer.UV4Kind
  19741. * - BABYLON.VertexBuffer.UV5Kind
  19742. * - BABYLON.VertexBuffer.UV6Kind
  19743. * - BABYLON.VertexBuffer.ColorKind
  19744. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19745. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19746. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19747. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19748. *
  19749. * Returns the Mesh.
  19750. */
  19751. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19752. return this;
  19753. };
  19754. /**
  19755. * Sets the mesh indices.
  19756. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19757. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19758. * This method creates a new index buffer each call.
  19759. * Returns the Mesh.
  19760. */
  19761. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19762. return this;
  19763. };
  19764. /** Returns false by default, used by the class Mesh.
  19765. * Returns a boolean
  19766. */
  19767. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19768. return false;
  19769. };
  19770. /**
  19771. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19772. * Returns a BoundingInfo
  19773. */
  19774. AbstractMesh.prototype.getBoundingInfo = function () {
  19775. if (this._masterMesh) {
  19776. return this._masterMesh.getBoundingInfo();
  19777. }
  19778. if (!this._boundingInfo) {
  19779. // this._boundingInfo is being created here
  19780. this._updateBoundingInfo();
  19781. }
  19782. // cannot be null.
  19783. return this._boundingInfo;
  19784. };
  19785. /**
  19786. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19787. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19788. */
  19789. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19790. if (includeDescendants === void 0) { includeDescendants = true; }
  19791. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19792. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19793. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19794. if (maxDimension === 0) {
  19795. return this;
  19796. }
  19797. var scale = 1 / maxDimension;
  19798. this.scaling.scaleInPlace(scale);
  19799. return this;
  19800. };
  19801. /**
  19802. * Sets a mesh new object BoundingInfo.
  19803. * Returns the AbstractMesh.
  19804. */
  19805. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19806. this._boundingInfo = boundingInfo;
  19807. return this;
  19808. };
  19809. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19810. get: function () {
  19811. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. AbstractMesh.prototype._preActivate = function () {
  19817. };
  19818. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19819. };
  19820. AbstractMesh.prototype._activate = function (renderId) {
  19821. this._renderId = renderId;
  19822. };
  19823. /**
  19824. * Returns the latest update of the World matrix
  19825. * Returns a Matrix.
  19826. */
  19827. AbstractMesh.prototype.getWorldMatrix = function () {
  19828. if (this._masterMesh) {
  19829. return this._masterMesh.getWorldMatrix();
  19830. }
  19831. return _super.prototype.getWorldMatrix.call(this);
  19832. };
  19833. /**
  19834. * Returns the latest update of the World matrix determinant.
  19835. */
  19836. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19837. if (this._masterMesh) {
  19838. return this._masterMesh._getWorldMatrixDeterminant();
  19839. }
  19840. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19841. };
  19842. // ================================== Point of View Movement =================================
  19843. /**
  19844. * Perform relative position change from the point of view of behind the front of the mesh.
  19845. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19846. * Supports definition of mesh facing forward or backward.
  19847. * @param {number} amountRight
  19848. * @param {number} amountUp
  19849. * @param {number} amountForward
  19850. *
  19851. * Returns the AbstractMesh.
  19852. */
  19853. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19854. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19855. return this;
  19856. };
  19857. /**
  19858. * Calculate relative position change from the point of view of behind the front of the mesh.
  19859. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19860. * Supports definition of mesh facing forward or backward.
  19861. * @param {number} amountRight
  19862. * @param {number} amountUp
  19863. * @param {number} amountForward
  19864. *
  19865. * Returns a new Vector3.
  19866. */
  19867. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19868. var rotMatrix = new BABYLON.Matrix();
  19869. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19870. rotQuaternion.toRotationMatrix(rotMatrix);
  19871. var translationDelta = BABYLON.Vector3.Zero();
  19872. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19873. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19874. return translationDelta;
  19875. };
  19876. // ================================== Point of View Rotation =================================
  19877. /**
  19878. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19879. * Supports definition of mesh facing forward or backward.
  19880. * @param {number} flipBack
  19881. * @param {number} twirlClockwise
  19882. * @param {number} tiltRight
  19883. *
  19884. * Returns the AbstractMesh.
  19885. */
  19886. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19887. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19888. return this;
  19889. };
  19890. /**
  19891. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19892. * Supports definition of mesh facing forward or backward.
  19893. * @param {number} flipBack
  19894. * @param {number} twirlClockwise
  19895. * @param {number} tiltRight
  19896. *
  19897. * Returns a new Vector3.
  19898. */
  19899. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19900. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19901. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19902. };
  19903. /**
  19904. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19905. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19906. */
  19907. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19908. if (includeDescendants === void 0) { includeDescendants = true; }
  19909. this.computeWorldMatrix(true);
  19910. var min;
  19911. var max;
  19912. var boundingInfo = this.getBoundingInfo();
  19913. if (!this.subMeshes) {
  19914. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19915. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19916. }
  19917. else {
  19918. min = boundingInfo.boundingBox.minimumWorld;
  19919. max = boundingInfo.boundingBox.maximumWorld;
  19920. }
  19921. if (includeDescendants) {
  19922. var descendants = this.getDescendants(false);
  19923. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19924. var descendant = descendants_1[_i];
  19925. var childMesh = descendant;
  19926. childMesh.computeWorldMatrix(true);
  19927. //make sure we have the needed params to get mix and max
  19928. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19929. continue;
  19930. }
  19931. var childBoundingInfo = childMesh.getBoundingInfo();
  19932. var boundingBox = childBoundingInfo.boundingBox;
  19933. var minBox = boundingBox.minimumWorld;
  19934. var maxBox = boundingBox.maximumWorld;
  19935. BABYLON.Tools.CheckExtends(minBox, min, max);
  19936. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19937. }
  19938. }
  19939. return {
  19940. min: min,
  19941. max: max
  19942. };
  19943. };
  19944. /**
  19945. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19946. * Returns the AbstractMesh.
  19947. */
  19948. AbstractMesh.prototype._updateBoundingInfo = function () {
  19949. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19950. this._boundingInfo.update(this.worldMatrixFromCache);
  19951. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19952. return this;
  19953. };
  19954. /**
  19955. * Update a mesh's children BoundingInfo objects only.
  19956. * Returns the AbstractMesh.
  19957. */
  19958. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19959. if (!this.subMeshes) {
  19960. return this;
  19961. }
  19962. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19963. var subMesh = this.subMeshes[subIndex];
  19964. if (!subMesh.IsGlobal) {
  19965. subMesh.updateBoundingInfo(matrix);
  19966. }
  19967. }
  19968. return this;
  19969. };
  19970. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19971. // Bounding info
  19972. this._updateBoundingInfo();
  19973. };
  19974. /**
  19975. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19976. * A mesh is in the frustum if its bounding box intersects the frustum.
  19977. * Boolean returned.
  19978. */
  19979. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19980. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19981. };
  19982. /**
  19983. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19984. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19985. * Boolean returned.
  19986. */
  19987. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19988. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19989. ;
  19990. };
  19991. /**
  19992. * True if the mesh intersects another mesh or a SolidParticle object.
  19993. * 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)
  19994. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19995. * Returns a boolean.
  19996. */
  19997. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19998. if (precise === void 0) { precise = false; }
  19999. if (!this._boundingInfo || !mesh._boundingInfo) {
  20000. return false;
  20001. }
  20002. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20003. return true;
  20004. }
  20005. if (includeDescendants) {
  20006. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20007. var child = _a[_i];
  20008. if (child.intersectsMesh(mesh, precise, true)) {
  20009. return true;
  20010. }
  20011. }
  20012. }
  20013. return false;
  20014. };
  20015. /**
  20016. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  20017. * Returns a boolean.
  20018. */
  20019. AbstractMesh.prototype.intersectsPoint = function (point) {
  20020. if (!this._boundingInfo) {
  20021. return false;
  20022. }
  20023. return this._boundingInfo.intersectsPoint(point);
  20024. };
  20025. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20026. return this.physicsImpostor;
  20027. };
  20028. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20029. if (camera === void 0) { camera = null; }
  20030. if (!camera) {
  20031. camera = this.getScene().activeCamera;
  20032. }
  20033. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20034. };
  20035. /**
  20036. * Returns the distance from the mesh to the active camera.
  20037. * Returns a float.
  20038. */
  20039. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20040. if (camera === void 0) { camera = null; }
  20041. if (!camera) {
  20042. camera = this.getScene().activeCamera;
  20043. }
  20044. return this.absolutePosition.subtract(camera.position).length();
  20045. };
  20046. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20047. if (!this.physicsImpostor) {
  20048. return this;
  20049. }
  20050. this.physicsImpostor.applyImpulse(force, contactPoint);
  20051. return this;
  20052. };
  20053. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20054. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20055. return this;
  20056. }
  20057. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20058. mainPivot: pivot1,
  20059. connectedPivot: pivot2,
  20060. nativeParams: options
  20061. });
  20062. return this;
  20063. };
  20064. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20065. // Collisions
  20066. /**
  20067. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20068. * Default `false`.
  20069. */
  20070. get: function () {
  20071. return this._checkCollisions;
  20072. },
  20073. set: function (collisionEnabled) {
  20074. this._checkCollisions = collisionEnabled;
  20075. if (this.getScene().workerCollisions) {
  20076. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20077. }
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20083. /**
  20084. * Gets Collider object used to compute collisions (not physics)
  20085. */
  20086. get: function () {
  20087. return this._collider;
  20088. },
  20089. enumerable: true,
  20090. configurable: true
  20091. });
  20092. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20093. var globalPosition = this.getAbsolutePosition();
  20094. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20095. if (!this._collider) {
  20096. this._collider = new BABYLON.Collider();
  20097. }
  20098. this._collider._radius = this.ellipsoid;
  20099. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20100. return this;
  20101. };
  20102. // Submeshes octree
  20103. /**
  20104. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20105. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20106. * Returns an Octree of submeshes.
  20107. */
  20108. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20109. if (maxCapacity === void 0) { maxCapacity = 64; }
  20110. if (maxDepth === void 0) { maxDepth = 2; }
  20111. if (!this._submeshesOctree) {
  20112. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20113. }
  20114. this.computeWorldMatrix(true);
  20115. var boundingInfo = this.getBoundingInfo();
  20116. // Update octree
  20117. var bbox = boundingInfo.boundingBox;
  20118. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20119. return this._submeshesOctree;
  20120. };
  20121. // Collisions
  20122. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20123. this._generatePointsArray();
  20124. if (!this._positions) {
  20125. return this;
  20126. }
  20127. // Transformation
  20128. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20129. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20130. subMesh._lastColliderWorldVertices = [];
  20131. subMesh._trianglePlanes = [];
  20132. var start = subMesh.verticesStart;
  20133. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20134. for (var i = start; i < end; i++) {
  20135. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20136. }
  20137. }
  20138. // Collide
  20139. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20140. if (collider.collisionFound) {
  20141. collider.collidedMesh = this;
  20142. }
  20143. return this;
  20144. };
  20145. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20146. var subMeshes;
  20147. var len;
  20148. // Octrees
  20149. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20150. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20151. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20152. len = intersections.length;
  20153. subMeshes = intersections.data;
  20154. }
  20155. else {
  20156. subMeshes = this.subMeshes;
  20157. len = subMeshes.length;
  20158. }
  20159. for (var index = 0; index < len; index++) {
  20160. var subMesh = subMeshes[index];
  20161. // Bounding test
  20162. if (len > 1 && !subMesh._checkCollision(collider))
  20163. continue;
  20164. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20165. }
  20166. return this;
  20167. };
  20168. AbstractMesh.prototype._checkCollision = function (collider) {
  20169. // Bounding box test
  20170. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20171. return this;
  20172. // Transformation matrix
  20173. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20174. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20175. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20176. return this;
  20177. };
  20178. // Picking
  20179. AbstractMesh.prototype._generatePointsArray = function () {
  20180. return false;
  20181. };
  20182. /**
  20183. * Checks if the passed Ray intersects with the mesh.
  20184. * Returns an object PickingInfo.
  20185. */
  20186. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20187. var pickingInfo = new BABYLON.PickingInfo();
  20188. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20189. return pickingInfo;
  20190. }
  20191. if (!this._generatePointsArray()) {
  20192. return pickingInfo;
  20193. }
  20194. var intersectInfo = null;
  20195. // Octrees
  20196. var subMeshes;
  20197. var len;
  20198. if (this._submeshesOctree && this.useOctreeForPicking) {
  20199. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20200. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20201. len = intersections.length;
  20202. subMeshes = intersections.data;
  20203. }
  20204. else {
  20205. subMeshes = this.subMeshes;
  20206. len = subMeshes.length;
  20207. }
  20208. for (var index = 0; index < len; index++) {
  20209. var subMesh = subMeshes[index];
  20210. // Bounding test
  20211. if (len > 1 && !subMesh.canIntersects(ray))
  20212. continue;
  20213. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20214. if (currentIntersectInfo) {
  20215. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20216. intersectInfo = currentIntersectInfo;
  20217. intersectInfo.subMeshId = index;
  20218. if (fastCheck) {
  20219. break;
  20220. }
  20221. }
  20222. }
  20223. }
  20224. if (intersectInfo) {
  20225. // Get picked point
  20226. var world = this.getWorldMatrix();
  20227. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20228. var direction = ray.direction.clone();
  20229. direction = direction.scale(intersectInfo.distance);
  20230. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20231. var pickedPoint = worldOrigin.add(worldDirection);
  20232. // Return result
  20233. pickingInfo.hit = true;
  20234. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20235. pickingInfo.pickedPoint = pickedPoint;
  20236. pickingInfo.pickedMesh = this;
  20237. pickingInfo.bu = intersectInfo.bu || 0;
  20238. pickingInfo.bv = intersectInfo.bv || 0;
  20239. pickingInfo.faceId = intersectInfo.faceId;
  20240. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20241. return pickingInfo;
  20242. }
  20243. return pickingInfo;
  20244. };
  20245. /**
  20246. * Clones the mesh, used by the class Mesh.
  20247. * Just returns `null` for an AbstractMesh.
  20248. */
  20249. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20250. return null;
  20251. };
  20252. /**
  20253. * Disposes all the mesh submeshes.
  20254. * Returns the AbstractMesh.
  20255. */
  20256. AbstractMesh.prototype.releaseSubMeshes = function () {
  20257. if (this.subMeshes) {
  20258. while (this.subMeshes.length) {
  20259. this.subMeshes[0].dispose();
  20260. }
  20261. }
  20262. else {
  20263. this.subMeshes = new Array();
  20264. }
  20265. return this;
  20266. };
  20267. /**
  20268. * Releases resources associated with this abstract mesh.
  20269. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20270. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20271. */
  20272. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20273. var _this = this;
  20274. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20275. var index;
  20276. // Smart Array Retainers.
  20277. this.getScene().freeActiveMeshes();
  20278. this.getScene().freeRenderingGroups();
  20279. // Action manager
  20280. if (this.actionManager !== undefined && this.actionManager !== null) {
  20281. this.actionManager.dispose();
  20282. this.actionManager = null;
  20283. }
  20284. // Skeleton
  20285. this._skeleton = null;
  20286. // Physics
  20287. if (this.physicsImpostor) {
  20288. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20289. }
  20290. // Intersections in progress
  20291. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20292. var other = this._intersectionsInProgress[index];
  20293. var pos = other._intersectionsInProgress.indexOf(this);
  20294. other._intersectionsInProgress.splice(pos, 1);
  20295. }
  20296. this._intersectionsInProgress = [];
  20297. // Lights
  20298. var lights = this.getScene().lights;
  20299. lights.forEach(function (light) {
  20300. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20301. if (meshIndex !== -1) {
  20302. light.includedOnlyMeshes.splice(meshIndex, 1);
  20303. }
  20304. meshIndex = light.excludedMeshes.indexOf(_this);
  20305. if (meshIndex !== -1) {
  20306. light.excludedMeshes.splice(meshIndex, 1);
  20307. }
  20308. // Shadow generators
  20309. var generator = light.getShadowGenerator();
  20310. if (generator) {
  20311. var shadowMap = generator.getShadowMap();
  20312. if (shadowMap && shadowMap.renderList) {
  20313. meshIndex = shadowMap.renderList.indexOf(_this);
  20314. if (meshIndex !== -1) {
  20315. shadowMap.renderList.splice(meshIndex, 1);
  20316. }
  20317. }
  20318. }
  20319. });
  20320. // Edges
  20321. if (this._edgesRenderer) {
  20322. this._edgesRenderer.dispose();
  20323. this._edgesRenderer = null;
  20324. }
  20325. // SubMeshes
  20326. if (this.getClassName() !== "InstancedMesh") {
  20327. this.releaseSubMeshes();
  20328. }
  20329. // Octree
  20330. var sceneOctree = this.getScene().selectionOctree;
  20331. if (sceneOctree !== undefined && sceneOctree !== null) {
  20332. var index = sceneOctree.dynamicContent.indexOf(this);
  20333. if (index !== -1) {
  20334. sceneOctree.dynamicContent.splice(index, 1);
  20335. }
  20336. }
  20337. // Query
  20338. var engine = this.getScene().getEngine();
  20339. if (this._occlusionQuery) {
  20340. this._isOcclusionQueryInProgress = false;
  20341. engine.deleteQuery(this._occlusionQuery);
  20342. this._occlusionQuery = null;
  20343. }
  20344. // Engine
  20345. engine.wipeCaches();
  20346. // Remove from scene
  20347. this.getScene().removeMesh(this);
  20348. if (disposeMaterialAndTextures) {
  20349. if (this.material) {
  20350. this.material.dispose(false, true);
  20351. }
  20352. }
  20353. if (!doNotRecurse) {
  20354. // Particles
  20355. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20356. if (this.getScene().particleSystems[index].emitter === this) {
  20357. this.getScene().particleSystems[index].dispose();
  20358. index--;
  20359. }
  20360. }
  20361. }
  20362. // facet data
  20363. if (this._facetDataEnabled) {
  20364. this.disableFacetData();
  20365. }
  20366. this.onAfterWorldMatrixUpdateObservable.clear();
  20367. this.onCollideObservable.clear();
  20368. this.onCollisionPositionChangeObservable.clear();
  20369. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20370. };
  20371. /**
  20372. * Adds the passed mesh as a child to the current mesh.
  20373. * Returns the AbstractMesh.
  20374. */
  20375. AbstractMesh.prototype.addChild = function (mesh) {
  20376. mesh.setParent(this);
  20377. return this;
  20378. };
  20379. /**
  20380. * Removes the passed mesh from the current mesh children list.
  20381. * Returns the AbstractMesh.
  20382. */
  20383. AbstractMesh.prototype.removeChild = function (mesh) {
  20384. mesh.setParent(null);
  20385. return this;
  20386. };
  20387. // Facet data
  20388. /**
  20389. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20390. * Returns the AbstractMesh.
  20391. */
  20392. AbstractMesh.prototype._initFacetData = function () {
  20393. if (!this._facetNormals) {
  20394. this._facetNormals = new Array();
  20395. }
  20396. if (!this._facetPositions) {
  20397. this._facetPositions = new Array();
  20398. }
  20399. if (!this._facetPartitioning) {
  20400. this._facetPartitioning = new Array();
  20401. }
  20402. this._facetNb = (this.getIndices().length / 3) | 0;
  20403. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20404. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20405. for (var f = 0; f < this._facetNb; f++) {
  20406. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20407. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20408. }
  20409. this._facetDataEnabled = true;
  20410. return this;
  20411. };
  20412. /**
  20413. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20414. * This method can be called within the render loop.
  20415. * 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.
  20416. * Returns the AbstractMesh.
  20417. */
  20418. AbstractMesh.prototype.updateFacetData = function () {
  20419. if (!this._facetDataEnabled) {
  20420. this._initFacetData();
  20421. }
  20422. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20423. var indices = this.getIndices();
  20424. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20425. var bInfo = this.getBoundingInfo();
  20426. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20427. // init arrays, matrix and sort function on first call
  20428. this._facetDepthSortEnabled = true;
  20429. if (indices instanceof Uint16Array) {
  20430. this._depthSortedIndices = new Uint16Array(indices);
  20431. }
  20432. else if (indices instanceof Uint32Array) {
  20433. this._depthSortedIndices = new Uint32Array(indices);
  20434. }
  20435. else {
  20436. var needs32bits = false;
  20437. for (var i = 0; i < indices.length; i++) {
  20438. if (indices[i] > 65535) {
  20439. needs32bits = true;
  20440. break;
  20441. }
  20442. }
  20443. if (needs32bits) {
  20444. this._depthSortedIndices = new Uint32Array(indices);
  20445. }
  20446. else {
  20447. this._depthSortedIndices = new Uint16Array(indices);
  20448. }
  20449. }
  20450. this._facetDepthSortFunction = function (f1, f2) {
  20451. return (f2.sqDistance - f1.sqDistance);
  20452. };
  20453. if (!this._facetDepthSortFrom) {
  20454. var camera = this.getScene().activeCamera;
  20455. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20456. }
  20457. this._depthSortedFacets = [];
  20458. for (var f = 0; f < this._facetNb; f++) {
  20459. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20460. this._depthSortedFacets.push(depthSortedFacet);
  20461. }
  20462. this._invertedMatrix = BABYLON.Matrix.Identity();
  20463. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20464. }
  20465. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20466. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20467. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20468. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20469. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20470. this._subDiv.max = this._partitioningSubdivisions;
  20471. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20472. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20473. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20474. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20475. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20476. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20477. // set the parameters for ComputeNormals()
  20478. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20479. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20480. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20481. this._facetParameters.bInfo = bInfo;
  20482. this._facetParameters.bbSize = this._bbSize;
  20483. this._facetParameters.subDiv = this._subDiv;
  20484. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20485. this._facetParameters.depthSort = this._facetDepthSort;
  20486. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20487. this.computeWorldMatrix(true);
  20488. this._worldMatrix.invertToRef(this._invertedMatrix);
  20489. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20490. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20491. }
  20492. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20493. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20494. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20495. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20496. var l = (this._depthSortedIndices.length / 3) | 0;
  20497. for (var f = 0; f < l; f++) {
  20498. var sind = this._depthSortedFacets[f].ind;
  20499. this._depthSortedIndices[f * 3] = indices[sind];
  20500. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20501. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20502. }
  20503. this.updateIndices(this._depthSortedIndices);
  20504. }
  20505. return this;
  20506. };
  20507. /**
  20508. * Returns the facetLocalNormals array.
  20509. * The normals are expressed in the mesh local space.
  20510. */
  20511. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20512. if (!this._facetNormals) {
  20513. this.updateFacetData();
  20514. }
  20515. return this._facetNormals;
  20516. };
  20517. /**
  20518. * Returns the facetLocalPositions array.
  20519. * The facet positions are expressed in the mesh local space.
  20520. */
  20521. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20522. if (!this._facetPositions) {
  20523. this.updateFacetData();
  20524. }
  20525. return this._facetPositions;
  20526. };
  20527. /**
  20528. * Returns the facetLocalPartioning array.
  20529. */
  20530. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20531. if (!this._facetPartitioning) {
  20532. this.updateFacetData();
  20533. }
  20534. return this._facetPartitioning;
  20535. };
  20536. /**
  20537. * Returns the i-th facet position in the world system.
  20538. * This method allocates a new Vector3 per call.
  20539. */
  20540. AbstractMesh.prototype.getFacetPosition = function (i) {
  20541. var pos = BABYLON.Vector3.Zero();
  20542. this.getFacetPositionToRef(i, pos);
  20543. return pos;
  20544. };
  20545. /**
  20546. * Sets the reference Vector3 with the i-th facet position in the world system.
  20547. * Returns the AbstractMesh.
  20548. */
  20549. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20550. var localPos = (this.getFacetLocalPositions())[i];
  20551. var world = this.getWorldMatrix();
  20552. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20553. return this;
  20554. };
  20555. /**
  20556. * Returns the i-th facet normal in the world system.
  20557. * This method allocates a new Vector3 per call.
  20558. */
  20559. AbstractMesh.prototype.getFacetNormal = function (i) {
  20560. var norm = BABYLON.Vector3.Zero();
  20561. this.getFacetNormalToRef(i, norm);
  20562. return norm;
  20563. };
  20564. /**
  20565. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20566. * Returns the AbstractMesh.
  20567. */
  20568. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20569. var localNorm = (this.getFacetLocalNormals())[i];
  20570. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20571. return this;
  20572. };
  20573. /**
  20574. * 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).
  20575. */
  20576. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20577. var bInfo = this.getBoundingInfo();
  20578. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20579. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20580. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20581. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20582. return null;
  20583. }
  20584. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20585. };
  20586. /**
  20587. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20588. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20589. * 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.
  20590. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20591. * 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.
  20592. */
  20593. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20594. if (checkFace === void 0) { checkFace = false; }
  20595. if (facing === void 0) { facing = true; }
  20596. var world = this.getWorldMatrix();
  20597. var invMat = BABYLON.Tmp.Matrix[5];
  20598. world.invertToRef(invMat);
  20599. var invVect = BABYLON.Tmp.Vector3[8];
  20600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20601. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20602. if (projected) {
  20603. // tranform the local computed projected vector to world coordinates
  20604. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20605. }
  20606. return closest;
  20607. };
  20608. /**
  20609. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20610. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20611. * 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.
  20612. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20613. * 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.
  20614. */
  20615. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20616. if (checkFace === void 0) { checkFace = false; }
  20617. if (facing === void 0) { facing = true; }
  20618. var closest = null;
  20619. var tmpx = 0.0;
  20620. var tmpy = 0.0;
  20621. var tmpz = 0.0;
  20622. var d = 0.0; // tmp dot facet normal * facet position
  20623. var t0 = 0.0;
  20624. var projx = 0.0;
  20625. var projy = 0.0;
  20626. var projz = 0.0;
  20627. // Get all the facets in the same partitioning block than (x, y, z)
  20628. var facetPositions = this.getFacetLocalPositions();
  20629. var facetNormals = this.getFacetLocalNormals();
  20630. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20631. if (!facetsInBlock) {
  20632. return null;
  20633. }
  20634. // Get the closest facet to (x, y, z)
  20635. var shortest = Number.MAX_VALUE; // init distance vars
  20636. var tmpDistance = shortest;
  20637. var fib; // current facet in the block
  20638. var norm; // current facet normal
  20639. var p0; // current facet barycenter position
  20640. // loop on all the facets in the current partitioning block
  20641. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20642. fib = facetsInBlock[idx];
  20643. norm = facetNormals[fib];
  20644. p0 = facetPositions[fib];
  20645. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20646. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20647. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20648. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20649. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20650. projx = x + norm.x * t0;
  20651. projy = y + norm.y * t0;
  20652. projz = z + norm.z * t0;
  20653. tmpx = projx - x;
  20654. tmpy = projy - y;
  20655. tmpz = projz - z;
  20656. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20657. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20658. shortest = tmpDistance;
  20659. closest = fib;
  20660. if (projected) {
  20661. projected.x = projx;
  20662. projected.y = projy;
  20663. projected.z = projz;
  20664. }
  20665. }
  20666. }
  20667. }
  20668. return closest;
  20669. };
  20670. /**
  20671. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20672. */
  20673. AbstractMesh.prototype.getFacetDataParameters = function () {
  20674. return this._facetParameters;
  20675. };
  20676. /**
  20677. * Disables the feature FacetData and frees the related memory.
  20678. * Returns the AbstractMesh.
  20679. */
  20680. AbstractMesh.prototype.disableFacetData = function () {
  20681. if (this._facetDataEnabled) {
  20682. this._facetDataEnabled = false;
  20683. this._facetPositions = new Array();
  20684. this._facetNormals = new Array();
  20685. this._facetPartitioning = new Array();
  20686. this._facetParameters = null;
  20687. this._depthSortedIndices = new Uint32Array(0);
  20688. }
  20689. return this;
  20690. };
  20691. /**
  20692. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20693. * Returns the mesh.
  20694. */
  20695. AbstractMesh.prototype.updateIndices = function (indices) {
  20696. return this;
  20697. };
  20698. /**
  20699. * The mesh Geometry. Actually used by the Mesh object.
  20700. * Returns a blank geometry object.
  20701. */
  20702. /**
  20703. * Creates new normals data for the mesh.
  20704. * @param updatable.
  20705. */
  20706. AbstractMesh.prototype.createNormals = function (updatable) {
  20707. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20708. var indices = this.getIndices();
  20709. var normals;
  20710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20711. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20712. }
  20713. else {
  20714. normals = [];
  20715. }
  20716. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20717. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20718. };
  20719. /**
  20720. * Align the mesh with a normal.
  20721. * Returns the mesh.
  20722. */
  20723. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20724. if (!upDirection) {
  20725. upDirection = BABYLON.Axis.Y;
  20726. }
  20727. var axisX = BABYLON.Tmp.Vector3[0];
  20728. var axisZ = BABYLON.Tmp.Vector3[1];
  20729. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20730. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20731. if (this.rotationQuaternion) {
  20732. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20733. }
  20734. else {
  20735. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20736. }
  20737. return this;
  20738. };
  20739. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20740. var engine = this.getEngine();
  20741. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20742. this._isOccluded = false;
  20743. return;
  20744. }
  20745. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20746. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20747. if (isOcclusionQueryAvailable) {
  20748. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20749. this._isOcclusionQueryInProgress = false;
  20750. this._occlusionInternalRetryCounter = 0;
  20751. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20752. }
  20753. else {
  20754. this._occlusionInternalRetryCounter++;
  20755. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20756. this._isOcclusionQueryInProgress = false;
  20757. this._occlusionInternalRetryCounter = 0;
  20758. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20759. // if strict continue the last state of the object.
  20760. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20761. }
  20762. else {
  20763. return;
  20764. }
  20765. }
  20766. }
  20767. var scene = this.getScene();
  20768. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20769. if (!this._occlusionQuery) {
  20770. this._occlusionQuery = engine.createQuery();
  20771. }
  20772. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20773. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20774. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20775. this._isOcclusionQueryInProgress = true;
  20776. };
  20777. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20778. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20779. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20780. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20781. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20782. return AbstractMesh;
  20783. }(BABYLON.TransformNode));
  20784. BABYLON.AbstractMesh = AbstractMesh;
  20785. })(BABYLON || (BABYLON = {}));
  20786. //# sourceMappingURL=babylon.abstractMesh.js.map
  20787. var BABYLON;
  20788. (function (BABYLON) {
  20789. /**
  20790. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20791. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20792. * 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.
  20793. */
  20794. var Light = /** @class */ (function (_super) {
  20795. __extends(Light, _super);
  20796. /**
  20797. * Creates a Light object in the scene.
  20798. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20799. * @param name The firendly name of the light
  20800. * @param scene The scene the light belongs too
  20801. */
  20802. function Light(name, scene) {
  20803. var _this = _super.call(this, name, scene) || this;
  20804. /**
  20805. * Diffuse gives the basic color to an object.
  20806. */
  20807. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20808. /**
  20809. * Specular produces a highlight color on an object.
  20810. * Note: This is note affecting PBR materials.
  20811. */
  20812. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20813. /**
  20814. * Strength of the light.
  20815. * Note: By default it is define in the framework own unit.
  20816. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20817. */
  20818. _this.intensity = 1.0;
  20819. /**
  20820. * Defines how far from the source the light is impacting in scene units.
  20821. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20822. */
  20823. _this.range = Number.MAX_VALUE;
  20824. /**
  20825. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20826. * of light.
  20827. */
  20828. _this._photometricScale = 1.0;
  20829. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20830. _this._radius = 0.00001;
  20831. /**
  20832. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20833. * exceeding the number allowed of the materials.
  20834. */
  20835. _this.renderPriority = 0;
  20836. /**
  20837. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20838. * the current shadow generator.
  20839. */
  20840. _this.shadowEnabled = true;
  20841. _this._excludeWithLayerMask = 0;
  20842. _this._includeOnlyWithLayerMask = 0;
  20843. _this._lightmapMode = 0;
  20844. /**
  20845. * @ignore Internal use only.
  20846. */
  20847. _this._excludedMeshesIds = new Array();
  20848. /**
  20849. * @ignore Internal use only.
  20850. */
  20851. _this._includedOnlyMeshesIds = new Array();
  20852. _this.getScene().addLight(_this);
  20853. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20854. _this._buildUniformLayout();
  20855. _this.includedOnlyMeshes = new Array();
  20856. _this.excludedMeshes = new Array();
  20857. _this._resyncMeshes();
  20858. return _this;
  20859. }
  20860. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20861. /**
  20862. * If every light affecting the material is in this lightmapMode,
  20863. * material.lightmapTexture adds or multiplies
  20864. * (depends on material.useLightmapAsShadowmap)
  20865. * after every other light calculations.
  20866. */
  20867. get: function () {
  20868. return Light._LIGHTMAP_DEFAULT;
  20869. },
  20870. enumerable: true,
  20871. configurable: true
  20872. });
  20873. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20874. /**
  20875. * material.lightmapTexture as only diffuse lighting from this light
  20876. * adds only specular lighting from this light
  20877. * adds dynamic shadows
  20878. */
  20879. get: function () {
  20880. return Light._LIGHTMAP_SPECULAR;
  20881. },
  20882. enumerable: true,
  20883. configurable: true
  20884. });
  20885. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20886. /**
  20887. * material.lightmapTexture as only lighting
  20888. * no light calculation from this light
  20889. * only adds dynamic shadows from this light
  20890. */
  20891. get: function () {
  20892. return Light._LIGHTMAP_SHADOWSONLY;
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20898. /**
  20899. * Each light type uses the default quantity according to its type:
  20900. * point/spot lights use luminous intensity
  20901. * directional lights use illuminance
  20902. */
  20903. get: function () {
  20904. return Light._INTENSITYMODE_AUTOMATIC;
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20910. /**
  20911. * lumen (lm)
  20912. */
  20913. get: function () {
  20914. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20915. },
  20916. enumerable: true,
  20917. configurable: true
  20918. });
  20919. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20920. /**
  20921. * candela (lm/sr)
  20922. */
  20923. get: function () {
  20924. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20925. },
  20926. enumerable: true,
  20927. configurable: true
  20928. });
  20929. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20930. /**
  20931. * lux (lm/m^2)
  20932. */
  20933. get: function () {
  20934. return Light._INTENSITYMODE_ILLUMINANCE;
  20935. },
  20936. enumerable: true,
  20937. configurable: true
  20938. });
  20939. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20940. /**
  20941. * nit (cd/m^2)
  20942. */
  20943. get: function () {
  20944. return Light._INTENSITYMODE_LUMINANCE;
  20945. },
  20946. enumerable: true,
  20947. configurable: true
  20948. });
  20949. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20950. /**
  20951. * Light type const id of the point light.
  20952. */
  20953. get: function () {
  20954. return Light._LIGHTTYPEID_POINTLIGHT;
  20955. },
  20956. enumerable: true,
  20957. configurable: true
  20958. });
  20959. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20960. /**
  20961. * Light type const id of the directional light.
  20962. */
  20963. get: function () {
  20964. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20965. },
  20966. enumerable: true,
  20967. configurable: true
  20968. });
  20969. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20970. /**
  20971. * Light type const id of the spot light.
  20972. */
  20973. get: function () {
  20974. return Light._LIGHTTYPEID_SPOTLIGHT;
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20980. /**
  20981. * Light type const id of the hemispheric light.
  20982. */
  20983. get: function () {
  20984. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(Light.prototype, "intensityMode", {
  20990. /**
  20991. * Gets the photometric scale used to interpret the intensity.
  20992. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20993. */
  20994. get: function () {
  20995. return this._intensityMode;
  20996. },
  20997. /**
  20998. * Sets the photometric scale used to interpret the intensity.
  20999. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21000. */
  21001. set: function (value) {
  21002. this._intensityMode = value;
  21003. this._computePhotometricScale();
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. ;
  21009. ;
  21010. Object.defineProperty(Light.prototype, "radius", {
  21011. /**
  21012. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21013. */
  21014. get: function () {
  21015. return this._radius;
  21016. },
  21017. /**
  21018. * sets the light radius used by PBR Materials to simulate soft area lights.
  21019. */
  21020. set: function (value) {
  21021. this._radius = value;
  21022. this._computePhotometricScale();
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. ;
  21028. ;
  21029. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21030. /**
  21031. * Gets the only meshes impacted by this light.
  21032. */
  21033. get: function () {
  21034. return this._includedOnlyMeshes;
  21035. },
  21036. /**
  21037. * Sets the only meshes impacted by this light.
  21038. */
  21039. set: function (value) {
  21040. this._includedOnlyMeshes = value;
  21041. this._hookArrayForIncludedOnly(value);
  21042. },
  21043. enumerable: true,
  21044. configurable: true
  21045. });
  21046. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21047. /**
  21048. * Gets the meshes not impacted by this light.
  21049. */
  21050. get: function () {
  21051. return this._excludedMeshes;
  21052. },
  21053. /**
  21054. * Sets the meshes not impacted by this light.
  21055. */
  21056. set: function (value) {
  21057. this._excludedMeshes = value;
  21058. this._hookArrayForExcluded(value);
  21059. },
  21060. enumerable: true,
  21061. configurable: true
  21062. });
  21063. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21064. /**
  21065. * Gets the layer id use to find what meshes are not impacted by the light.
  21066. * Inactive if 0
  21067. */
  21068. get: function () {
  21069. return this._excludeWithLayerMask;
  21070. },
  21071. /**
  21072. * Sets the layer id use to find what meshes are not impacted by the light.
  21073. * Inactive if 0
  21074. */
  21075. set: function (value) {
  21076. this._excludeWithLayerMask = value;
  21077. this._resyncMeshes();
  21078. },
  21079. enumerable: true,
  21080. configurable: true
  21081. });
  21082. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21083. /**
  21084. * Gets the layer id use to find what meshes are impacted by the light.
  21085. * Inactive if 0
  21086. */
  21087. get: function () {
  21088. return this._includeOnlyWithLayerMask;
  21089. },
  21090. /**
  21091. * Sets the layer id use to find what meshes are impacted by the light.
  21092. * Inactive if 0
  21093. */
  21094. set: function (value) {
  21095. this._includeOnlyWithLayerMask = value;
  21096. this._resyncMeshes();
  21097. },
  21098. enumerable: true,
  21099. configurable: true
  21100. });
  21101. Object.defineProperty(Light.prototype, "lightmapMode", {
  21102. /**
  21103. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21104. */
  21105. get: function () {
  21106. return this._lightmapMode;
  21107. },
  21108. /**
  21109. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21110. */
  21111. set: function (value) {
  21112. if (this._lightmapMode === value) {
  21113. return;
  21114. }
  21115. this._lightmapMode = value;
  21116. this._markMeshesAsLightDirty();
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. /**
  21122. * Returns the string "Light".
  21123. * @returns the class name
  21124. */
  21125. Light.prototype.getClassName = function () {
  21126. return "Light";
  21127. };
  21128. /**
  21129. * Converts the light information to a readable string for debug purpose.
  21130. * @param fullDetails Supports for multiple levels of logging within scene loading
  21131. * @returns the human readable light info
  21132. */
  21133. Light.prototype.toString = function (fullDetails) {
  21134. var ret = "Name: " + this.name;
  21135. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21136. if (this.animations) {
  21137. for (var i = 0; i < this.animations.length; i++) {
  21138. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21139. }
  21140. }
  21141. if (fullDetails) {
  21142. }
  21143. return ret;
  21144. };
  21145. /**
  21146. * Set the enabled state of this node.
  21147. * @param value - the new enabled state
  21148. */
  21149. Light.prototype.setEnabled = function (value) {
  21150. _super.prototype.setEnabled.call(this, value);
  21151. this._resyncMeshes();
  21152. };
  21153. /**
  21154. * Returns the Light associated shadow generator if any.
  21155. * @return the associated shadow generator.
  21156. */
  21157. Light.prototype.getShadowGenerator = function () {
  21158. return this._shadowGenerator;
  21159. };
  21160. /**
  21161. * Returns a Vector3, the absolute light position in the World.
  21162. * @returns the world space position of the light
  21163. */
  21164. Light.prototype.getAbsolutePosition = function () {
  21165. return BABYLON.Vector3.Zero();
  21166. };
  21167. /**
  21168. * Specifies if the light will affect the passed mesh.
  21169. * @param mesh The mesh to test against the light
  21170. * @return true the mesh is affected otherwise, false.
  21171. */
  21172. Light.prototype.canAffectMesh = function (mesh) {
  21173. if (!mesh) {
  21174. return true;
  21175. }
  21176. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21177. return false;
  21178. }
  21179. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21180. return false;
  21181. }
  21182. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21183. return false;
  21184. }
  21185. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21186. return false;
  21187. }
  21188. return true;
  21189. };
  21190. /**
  21191. * Computes and Returns the light World matrix.
  21192. * @returns the world matrix
  21193. */
  21194. Light.prototype.getWorldMatrix = function () {
  21195. this._currentRenderId = this.getScene().getRenderId();
  21196. this._childRenderId = this._currentRenderId;
  21197. var worldMatrix = this._getWorldMatrix();
  21198. if (this.parent && this.parent.getWorldMatrix) {
  21199. if (!this._parentedWorldMatrix) {
  21200. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21201. }
  21202. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21203. this._markSyncedWithParent();
  21204. return this._parentedWorldMatrix;
  21205. }
  21206. return worldMatrix;
  21207. };
  21208. /**
  21209. * Sort function to order lights for rendering.
  21210. * @param a First Light object to compare to second.
  21211. * @param b Second Light object to compare first.
  21212. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21213. */
  21214. Light.CompareLightsPriority = function (a, b) {
  21215. //shadow-casting lights have priority over non-shadow-casting lights
  21216. //the renderPrioirty is a secondary sort criterion
  21217. if (a.shadowEnabled !== b.shadowEnabled) {
  21218. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21219. }
  21220. return b.renderPriority - a.renderPriority;
  21221. };
  21222. /**
  21223. * Releases resources associated with this node.
  21224. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21225. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21226. */
  21227. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21228. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21229. if (this._shadowGenerator) {
  21230. this._shadowGenerator.dispose();
  21231. this._shadowGenerator = null;
  21232. }
  21233. // Animations
  21234. this.getScene().stopAnimation(this);
  21235. // Remove from meshes
  21236. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21237. var mesh = _a[_i];
  21238. mesh._removeLightSource(this);
  21239. }
  21240. this._uniformBuffer.dispose();
  21241. // Remove from scene
  21242. this.getScene().removeLight(this);
  21243. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21244. };
  21245. /**
  21246. * Returns the light type ID (integer).
  21247. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21248. */
  21249. Light.prototype.getTypeID = function () {
  21250. return 0;
  21251. };
  21252. /**
  21253. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21254. * @returns the scaled intensity in intensity mode unit
  21255. */
  21256. Light.prototype.getScaledIntensity = function () {
  21257. return this._photometricScale * this.intensity;
  21258. };
  21259. /**
  21260. * Returns a new Light object, named "name", from the current one.
  21261. * @param name The name of the cloned light
  21262. * @returns the new created light
  21263. */
  21264. Light.prototype.clone = function (name) {
  21265. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21266. if (!constructor) {
  21267. return null;
  21268. }
  21269. return BABYLON.SerializationHelper.Clone(constructor, this);
  21270. };
  21271. /**
  21272. * Serializes the current light into a Serialization object.
  21273. * @returns the serialized object.
  21274. */
  21275. Light.prototype.serialize = function () {
  21276. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21277. // Type
  21278. serializationObject.type = this.getTypeID();
  21279. // Parent
  21280. if (this.parent) {
  21281. serializationObject.parentId = this.parent.id;
  21282. }
  21283. // Inclusion / exclusions
  21284. if (this.excludedMeshes.length > 0) {
  21285. serializationObject.excludedMeshesIds = [];
  21286. this.excludedMeshes.forEach(function (mesh) {
  21287. serializationObject.excludedMeshesIds.push(mesh.id);
  21288. });
  21289. }
  21290. if (this.includedOnlyMeshes.length > 0) {
  21291. serializationObject.includedOnlyMeshesIds = [];
  21292. this.includedOnlyMeshes.forEach(function (mesh) {
  21293. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21294. });
  21295. }
  21296. // Animations
  21297. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21298. serializationObject.ranges = this.serializeAnimationRanges();
  21299. return serializationObject;
  21300. };
  21301. /**
  21302. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21303. * This new light is named "name" and added to the passed scene.
  21304. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21305. * @param name The friendly name of the light
  21306. * @param scene The scene the new light will belong to
  21307. * @returns the constructor function
  21308. */
  21309. Light.GetConstructorFromName = function (type, name, scene) {
  21310. switch (type) {
  21311. case 0:
  21312. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21313. case 1:
  21314. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21315. case 2:
  21316. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21317. case 3:
  21318. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21319. }
  21320. return null;
  21321. };
  21322. /**
  21323. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21324. * @param parsedLight The JSON representation of the light
  21325. * @param scene The scene to create the parsed light in
  21326. * @returns the created light after parsing
  21327. */
  21328. Light.Parse = function (parsedLight, scene) {
  21329. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21330. if (!constructor) {
  21331. return null;
  21332. }
  21333. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21334. // Inclusion / exclusions
  21335. if (parsedLight.excludedMeshesIds) {
  21336. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21337. }
  21338. if (parsedLight.includedOnlyMeshesIds) {
  21339. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21340. }
  21341. // Parent
  21342. if (parsedLight.parentId) {
  21343. light._waitingParentId = parsedLight.parentId;
  21344. }
  21345. // Animations
  21346. if (parsedLight.animations) {
  21347. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21348. var parsedAnimation = parsedLight.animations[animationIndex];
  21349. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21350. }
  21351. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21352. }
  21353. if (parsedLight.autoAnimate) {
  21354. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21355. }
  21356. return light;
  21357. };
  21358. Light.prototype._hookArrayForExcluded = function (array) {
  21359. var _this = this;
  21360. var oldPush = array.push;
  21361. array.push = function () {
  21362. var items = [];
  21363. for (var _i = 0; _i < arguments.length; _i++) {
  21364. items[_i] = arguments[_i];
  21365. }
  21366. var result = oldPush.apply(array, items);
  21367. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21368. var item = items_1[_a];
  21369. item._resyncLighSource(_this);
  21370. }
  21371. return result;
  21372. };
  21373. var oldSplice = array.splice;
  21374. array.splice = function (index, deleteCount) {
  21375. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21376. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21377. var item = deleted_1[_i];
  21378. item._resyncLighSource(_this);
  21379. }
  21380. return deleted;
  21381. };
  21382. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21383. var item = array_1[_i];
  21384. item._resyncLighSource(this);
  21385. }
  21386. };
  21387. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21388. var _this = this;
  21389. var oldPush = array.push;
  21390. array.push = function () {
  21391. var items = [];
  21392. for (var _i = 0; _i < arguments.length; _i++) {
  21393. items[_i] = arguments[_i];
  21394. }
  21395. var result = oldPush.apply(array, items);
  21396. _this._resyncMeshes();
  21397. return result;
  21398. };
  21399. var oldSplice = array.splice;
  21400. array.splice = function (index, deleteCount) {
  21401. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21402. _this._resyncMeshes();
  21403. return deleted;
  21404. };
  21405. this._resyncMeshes();
  21406. };
  21407. Light.prototype._resyncMeshes = function () {
  21408. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21409. var mesh = _a[_i];
  21410. mesh._resyncLighSource(this);
  21411. }
  21412. };
  21413. /**
  21414. * Forces the meshes to update their light related information in their rendering used effects
  21415. * @ignore Internal Use Only
  21416. */
  21417. Light.prototype._markMeshesAsLightDirty = function () {
  21418. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21419. var mesh = _a[_i];
  21420. if (mesh._lightSources.indexOf(this) !== -1) {
  21421. mesh._markSubMeshesAsLightDirty();
  21422. }
  21423. }
  21424. };
  21425. /**
  21426. * Recomputes the cached photometric scale if needed.
  21427. */
  21428. Light.prototype._computePhotometricScale = function () {
  21429. this._photometricScale = this._getPhotometricScale();
  21430. this.getScene().resetCachedMaterial();
  21431. };
  21432. /**
  21433. * Returns the Photometric Scale according to the light type and intensity mode.
  21434. */
  21435. Light.prototype._getPhotometricScale = function () {
  21436. var photometricScale = 0.0;
  21437. var lightTypeID = this.getTypeID();
  21438. //get photometric mode
  21439. var photometricMode = this.intensityMode;
  21440. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21441. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21442. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21443. }
  21444. else {
  21445. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21446. }
  21447. }
  21448. //compute photometric scale
  21449. switch (lightTypeID) {
  21450. case Light.LIGHTTYPEID_POINTLIGHT:
  21451. case Light.LIGHTTYPEID_SPOTLIGHT:
  21452. switch (photometricMode) {
  21453. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21454. photometricScale = 1.0 / (4.0 * Math.PI);
  21455. break;
  21456. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21457. photometricScale = 1.0;
  21458. break;
  21459. case Light.INTENSITYMODE_LUMINANCE:
  21460. photometricScale = this.radius * this.radius;
  21461. break;
  21462. }
  21463. break;
  21464. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21465. switch (photometricMode) {
  21466. case Light.INTENSITYMODE_ILLUMINANCE:
  21467. photometricScale = 1.0;
  21468. break;
  21469. case Light.INTENSITYMODE_LUMINANCE:
  21470. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21471. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21472. var apexAngleRadians = this.radius;
  21473. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21474. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21475. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21476. photometricScale = solidAngle;
  21477. break;
  21478. }
  21479. break;
  21480. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21481. // No fall off in hemisperic light.
  21482. photometricScale = 1.0;
  21483. break;
  21484. }
  21485. return photometricScale;
  21486. };
  21487. /**
  21488. * Reorder the light in the scene according to their defined priority.
  21489. * @ignore Internal Use Only
  21490. */
  21491. Light.prototype._reorderLightsInScene = function () {
  21492. var scene = this.getScene();
  21493. if (this._renderPriority != 0) {
  21494. scene.requireLightSorting = true;
  21495. }
  21496. this.getScene().sortLightsByPriority();
  21497. };
  21498. //lightmapMode Consts
  21499. Light._LIGHTMAP_DEFAULT = 0;
  21500. Light._LIGHTMAP_SPECULAR = 1;
  21501. Light._LIGHTMAP_SHADOWSONLY = 2;
  21502. // Intensity Mode Consts
  21503. Light._INTENSITYMODE_AUTOMATIC = 0;
  21504. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21505. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21506. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21507. Light._INTENSITYMODE_LUMINANCE = 4;
  21508. // Light types ids const.
  21509. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21510. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21511. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21512. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21513. __decorate([
  21514. BABYLON.serializeAsColor3()
  21515. ], Light.prototype, "diffuse", void 0);
  21516. __decorate([
  21517. BABYLON.serializeAsColor3()
  21518. ], Light.prototype, "specular", void 0);
  21519. __decorate([
  21520. BABYLON.serialize()
  21521. ], Light.prototype, "intensity", void 0);
  21522. __decorate([
  21523. BABYLON.serialize()
  21524. ], Light.prototype, "range", void 0);
  21525. __decorate([
  21526. BABYLON.serialize()
  21527. ], Light.prototype, "intensityMode", null);
  21528. __decorate([
  21529. BABYLON.serialize()
  21530. ], Light.prototype, "radius", null);
  21531. __decorate([
  21532. BABYLON.serialize()
  21533. ], Light.prototype, "_renderPriority", void 0);
  21534. __decorate([
  21535. BABYLON.expandToProperty("_reorderLightsInScene")
  21536. ], Light.prototype, "renderPriority", void 0);
  21537. __decorate([
  21538. BABYLON.serialize()
  21539. ], Light.prototype, "shadowEnabled", void 0);
  21540. __decorate([
  21541. BABYLON.serialize("excludeWithLayerMask")
  21542. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21543. __decorate([
  21544. BABYLON.serialize("includeOnlyWithLayerMask")
  21545. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21546. __decorate([
  21547. BABYLON.serialize("lightmapMode")
  21548. ], Light.prototype, "_lightmapMode", void 0);
  21549. return Light;
  21550. }(BABYLON.Node));
  21551. BABYLON.Light = Light;
  21552. })(BABYLON || (BABYLON = {}));
  21553. //# sourceMappingURL=babylon.light.js.map
  21554. var BABYLON;
  21555. (function (BABYLON) {
  21556. var Camera = /** @class */ (function (_super) {
  21557. __extends(Camera, _super);
  21558. function Camera(name, position, scene) {
  21559. var _this = _super.call(this, name, scene) || this;
  21560. /**
  21561. * The vector the camera should consider as up.
  21562. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21563. */
  21564. _this.upVector = BABYLON.Vector3.Up();
  21565. _this.orthoLeft = null;
  21566. _this.orthoRight = null;
  21567. _this.orthoBottom = null;
  21568. _this.orthoTop = null;
  21569. /**
  21570. * FOV is set in Radians. (default is 0.8)
  21571. */
  21572. _this.fov = 0.8;
  21573. _this.minZ = 1;
  21574. _this.maxZ = 10000.0;
  21575. _this.inertia = 0.9;
  21576. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21577. _this.isIntermediate = false;
  21578. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21579. /**
  21580. * Restricts the camera to viewing objects with the same layerMask.
  21581. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21582. */
  21583. _this.layerMask = 0x0FFFFFFF;
  21584. /**
  21585. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21586. */
  21587. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21588. // Camera rig members
  21589. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21590. _this._rigCameras = new Array();
  21591. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21592. _this._skipRendering = false;
  21593. _this.customRenderTargets = new Array();
  21594. // Observables
  21595. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21596. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21597. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21598. _this.onRestoreStateObservable = new BABYLON.Observable();
  21599. // Cache
  21600. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21601. _this._projectionMatrix = new BABYLON.Matrix();
  21602. _this._doNotComputeProjectionMatrix = false;
  21603. _this._postProcesses = new Array();
  21604. _this._transformMatrix = BABYLON.Matrix.Zero();
  21605. _this._activeMeshes = new BABYLON.SmartArray(256);
  21606. _this._globalPosition = BABYLON.Vector3.Zero();
  21607. _this._refreshFrustumPlanes = true;
  21608. _this.getScene().addCamera(_this);
  21609. if (!_this.getScene().activeCamera) {
  21610. _this.getScene().activeCamera = _this;
  21611. }
  21612. _this.position = position;
  21613. return _this;
  21614. }
  21615. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21616. get: function () {
  21617. return Camera._PERSPECTIVE_CAMERA;
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21623. get: function () {
  21624. return Camera._ORTHOGRAPHIC_CAMERA;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21630. /**
  21631. * This is the default FOV mode for perspective cameras.
  21632. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21633. *
  21634. */
  21635. get: function () {
  21636. return Camera._FOVMODE_VERTICAL_FIXED;
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21642. /**
  21643. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21644. *
  21645. */
  21646. get: function () {
  21647. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21653. get: function () {
  21654. return Camera._RIG_MODE_NONE;
  21655. },
  21656. enumerable: true,
  21657. configurable: true
  21658. });
  21659. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21660. get: function () {
  21661. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21667. get: function () {
  21668. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21674. get: function () {
  21675. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21676. },
  21677. enumerable: true,
  21678. configurable: true
  21679. });
  21680. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21681. get: function () {
  21682. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21688. get: function () {
  21689. return Camera._RIG_MODE_VR;
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21695. get: function () {
  21696. return Camera._RIG_MODE_WEBVR;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. /**
  21702. * Store current camera state (fov, position, etc..)
  21703. */
  21704. Camera.prototype.storeState = function () {
  21705. this._stateStored = true;
  21706. this._storedFov = this.fov;
  21707. return this;
  21708. };
  21709. /**
  21710. * Restores the camera state values if it has been stored. You must call storeState() first
  21711. */
  21712. Camera.prototype._restoreStateValues = function () {
  21713. if (!this._stateStored) {
  21714. return false;
  21715. }
  21716. this.fov = this._storedFov;
  21717. return true;
  21718. };
  21719. /**
  21720. * Restored camera state. You must call storeState() first
  21721. */
  21722. Camera.prototype.restoreState = function () {
  21723. if (this._restoreStateValues()) {
  21724. this.onRestoreStateObservable.notifyObservers(this);
  21725. return true;
  21726. }
  21727. return false;
  21728. };
  21729. Camera.prototype.getClassName = function () {
  21730. return "Camera";
  21731. };
  21732. /**
  21733. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21734. */
  21735. Camera.prototype.toString = function (fullDetails) {
  21736. var ret = "Name: " + this.name;
  21737. ret += ", type: " + this.getClassName();
  21738. if (this.animations) {
  21739. for (var i = 0; i < this.animations.length; i++) {
  21740. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21741. }
  21742. }
  21743. if (fullDetails) {
  21744. }
  21745. return ret;
  21746. };
  21747. Object.defineProperty(Camera.prototype, "globalPosition", {
  21748. get: function () {
  21749. return this._globalPosition;
  21750. },
  21751. enumerable: true,
  21752. configurable: true
  21753. });
  21754. Camera.prototype.getActiveMeshes = function () {
  21755. return this._activeMeshes;
  21756. };
  21757. Camera.prototype.isActiveMesh = function (mesh) {
  21758. return (this._activeMeshes.indexOf(mesh) !== -1);
  21759. };
  21760. /**
  21761. * Is this camera ready to be used/rendered
  21762. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21763. * @return true if the camera is ready
  21764. */
  21765. Camera.prototype.isReady = function (completeCheck) {
  21766. if (completeCheck === void 0) { completeCheck = false; }
  21767. if (completeCheck) {
  21768. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21769. var pp = _a[_i];
  21770. if (pp && !pp.isReady()) {
  21771. return false;
  21772. }
  21773. }
  21774. }
  21775. return _super.prototype.isReady.call(this, completeCheck);
  21776. };
  21777. //Cache
  21778. Camera.prototype._initCache = function () {
  21779. _super.prototype._initCache.call(this);
  21780. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21781. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21782. this._cache.mode = undefined;
  21783. this._cache.minZ = undefined;
  21784. this._cache.maxZ = undefined;
  21785. this._cache.fov = undefined;
  21786. this._cache.fovMode = undefined;
  21787. this._cache.aspectRatio = undefined;
  21788. this._cache.orthoLeft = undefined;
  21789. this._cache.orthoRight = undefined;
  21790. this._cache.orthoBottom = undefined;
  21791. this._cache.orthoTop = undefined;
  21792. this._cache.renderWidth = undefined;
  21793. this._cache.renderHeight = undefined;
  21794. };
  21795. Camera.prototype._updateCache = function (ignoreParentClass) {
  21796. if (!ignoreParentClass) {
  21797. _super.prototype._updateCache.call(this);
  21798. }
  21799. this._cache.position.copyFrom(this.position);
  21800. this._cache.upVector.copyFrom(this.upVector);
  21801. };
  21802. // Synchronized
  21803. Camera.prototype._isSynchronized = function () {
  21804. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21805. };
  21806. Camera.prototype._isSynchronizedViewMatrix = function () {
  21807. if (!_super.prototype._isSynchronized.call(this))
  21808. return false;
  21809. return this._cache.position.equals(this.position)
  21810. && this._cache.upVector.equals(this.upVector)
  21811. && this.isSynchronizedWithParent();
  21812. };
  21813. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21814. var check = this._cache.mode === this.mode
  21815. && this._cache.minZ === this.minZ
  21816. && this._cache.maxZ === this.maxZ;
  21817. if (!check) {
  21818. return false;
  21819. }
  21820. var engine = this.getEngine();
  21821. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21822. check = this._cache.fov === this.fov
  21823. && this._cache.fovMode === this.fovMode
  21824. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21825. }
  21826. else {
  21827. check = this._cache.orthoLeft === this.orthoLeft
  21828. && this._cache.orthoRight === this.orthoRight
  21829. && this._cache.orthoBottom === this.orthoBottom
  21830. && this._cache.orthoTop === this.orthoTop
  21831. && this._cache.renderWidth === engine.getRenderWidth()
  21832. && this._cache.renderHeight === engine.getRenderHeight();
  21833. }
  21834. return check;
  21835. };
  21836. // Controls
  21837. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21838. };
  21839. Camera.prototype.detachControl = function (element) {
  21840. };
  21841. Camera.prototype.update = function () {
  21842. this._checkInputs();
  21843. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21844. this._updateRigCameras();
  21845. }
  21846. };
  21847. Camera.prototype._checkInputs = function () {
  21848. this.onAfterCheckInputsObservable.notifyObservers(this);
  21849. };
  21850. Object.defineProperty(Camera.prototype, "rigCameras", {
  21851. get: function () {
  21852. return this._rigCameras;
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21858. get: function () {
  21859. return this._rigPostProcess;
  21860. },
  21861. enumerable: true,
  21862. configurable: true
  21863. });
  21864. /**
  21865. * Internal, gets the first post proces.
  21866. * @returns the first post process to be run on this camera.
  21867. */
  21868. Camera.prototype._getFirstPostProcess = function () {
  21869. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21870. if (this._postProcesses[ppIndex] !== null) {
  21871. return this._postProcesses[ppIndex];
  21872. }
  21873. }
  21874. return null;
  21875. };
  21876. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21877. // invalidate framebuffer
  21878. var firstPostProcess = this._getFirstPostProcess();
  21879. if (firstPostProcess) {
  21880. firstPostProcess.markTextureDirty();
  21881. }
  21882. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21883. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21884. var cam = this._rigCameras[i];
  21885. var rigPostProcess = cam._rigPostProcess;
  21886. // for VR rig, there does not have to be a post process
  21887. if (rigPostProcess) {
  21888. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21889. if (isPass) {
  21890. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21891. cam.isIntermediate = this._postProcesses.length === 0;
  21892. }
  21893. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21894. rigPostProcess.markTextureDirty();
  21895. }
  21896. else {
  21897. cam._postProcesses = this._postProcesses.slice(0);
  21898. }
  21899. }
  21900. };
  21901. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21902. if (insertAt === void 0) { insertAt = null; }
  21903. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21904. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21905. return 0;
  21906. }
  21907. if (insertAt == null || insertAt < 0) {
  21908. this._postProcesses.push(postProcess);
  21909. }
  21910. else if (this._postProcesses[insertAt] === null) {
  21911. this._postProcesses[insertAt] = postProcess;
  21912. }
  21913. else {
  21914. this._postProcesses.splice(insertAt, 0, postProcess);
  21915. }
  21916. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21917. return this._postProcesses.indexOf(postProcess);
  21918. };
  21919. Camera.prototype.detachPostProcess = function (postProcess) {
  21920. var idx = this._postProcesses.indexOf(postProcess);
  21921. if (idx !== -1) {
  21922. this._postProcesses[idx] = null;
  21923. }
  21924. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21925. };
  21926. Camera.prototype.getWorldMatrix = function () {
  21927. if (!this._worldMatrix) {
  21928. this._worldMatrix = BABYLON.Matrix.Identity();
  21929. }
  21930. var viewMatrix = this.getViewMatrix();
  21931. viewMatrix.invertToRef(this._worldMatrix);
  21932. return this._worldMatrix;
  21933. };
  21934. Camera.prototype._getViewMatrix = function () {
  21935. return BABYLON.Matrix.Identity();
  21936. };
  21937. Camera.prototype.getViewMatrix = function (force) {
  21938. if (!force && this._isSynchronizedViewMatrix()) {
  21939. return this._computedViewMatrix;
  21940. }
  21941. this.updateCache();
  21942. this._computedViewMatrix = this._getViewMatrix();
  21943. this._currentRenderId = this.getScene().getRenderId();
  21944. this._childRenderId = this._currentRenderId;
  21945. this._refreshFrustumPlanes = true;
  21946. if (!this.parent || !this.parent.getWorldMatrix) {
  21947. this._globalPosition.copyFrom(this.position);
  21948. }
  21949. else {
  21950. if (!this._worldMatrix) {
  21951. this._worldMatrix = BABYLON.Matrix.Identity();
  21952. }
  21953. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21954. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21955. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21956. this._computedViewMatrix.invert();
  21957. this._markSyncedWithParent();
  21958. }
  21959. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21960. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21961. }
  21962. this.onViewMatrixChangedObservable.notifyObservers(this);
  21963. return this._computedViewMatrix;
  21964. };
  21965. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21966. this._doNotComputeProjectionMatrix = true;
  21967. if (projection !== undefined) {
  21968. this._projectionMatrix = projection;
  21969. }
  21970. };
  21971. ;
  21972. Camera.prototype.unfreezeProjectionMatrix = function () {
  21973. this._doNotComputeProjectionMatrix = false;
  21974. };
  21975. ;
  21976. Camera.prototype.getProjectionMatrix = function (force) {
  21977. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21978. return this._projectionMatrix;
  21979. }
  21980. // Cache
  21981. this._cache.mode = this.mode;
  21982. this._cache.minZ = this.minZ;
  21983. this._cache.maxZ = this.maxZ;
  21984. // Matrix
  21985. this._refreshFrustumPlanes = true;
  21986. var engine = this.getEngine();
  21987. var scene = this.getScene();
  21988. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21989. this._cache.fov = this.fov;
  21990. this._cache.fovMode = this.fovMode;
  21991. this._cache.aspectRatio = engine.getAspectRatio(this);
  21992. if (this.minZ <= 0) {
  21993. this.minZ = 0.1;
  21994. }
  21995. if (scene.useRightHandedSystem) {
  21996. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21997. }
  21998. else {
  21999. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22000. }
  22001. }
  22002. else {
  22003. var halfWidth = engine.getRenderWidth() / 2.0;
  22004. var halfHeight = engine.getRenderHeight() / 2.0;
  22005. if (scene.useRightHandedSystem) {
  22006. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22007. }
  22008. else {
  22009. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22010. }
  22011. this._cache.orthoLeft = this.orthoLeft;
  22012. this._cache.orthoRight = this.orthoRight;
  22013. this._cache.orthoBottom = this.orthoBottom;
  22014. this._cache.orthoTop = this.orthoTop;
  22015. this._cache.renderWidth = engine.getRenderWidth();
  22016. this._cache.renderHeight = engine.getRenderHeight();
  22017. }
  22018. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22019. return this._projectionMatrix;
  22020. };
  22021. Camera.prototype.getTranformationMatrix = function () {
  22022. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22023. return this._transformMatrix;
  22024. };
  22025. Camera.prototype.updateFrustumPlanes = function () {
  22026. if (!this._refreshFrustumPlanes) {
  22027. return;
  22028. }
  22029. this.getTranformationMatrix();
  22030. if (!this._frustumPlanes) {
  22031. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22032. }
  22033. else {
  22034. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22035. }
  22036. this._refreshFrustumPlanes = false;
  22037. };
  22038. Camera.prototype.isInFrustum = function (target) {
  22039. this.updateFrustumPlanes();
  22040. return target.isInFrustum(this._frustumPlanes);
  22041. };
  22042. Camera.prototype.isCompletelyInFrustum = function (target) {
  22043. this.updateFrustumPlanes();
  22044. return target.isCompletelyInFrustum(this._frustumPlanes);
  22045. };
  22046. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22047. if (length === void 0) { length = 100; }
  22048. if (!transform) {
  22049. transform = this.getWorldMatrix();
  22050. }
  22051. if (!origin) {
  22052. origin = this.position;
  22053. }
  22054. var forward = new BABYLON.Vector3(0, 0, 1);
  22055. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22056. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22057. return new BABYLON.Ray(origin, direction, length);
  22058. };
  22059. /**
  22060. * Releases resources associated with this node.
  22061. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22062. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22063. */
  22064. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22065. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22066. // Observables
  22067. this.onViewMatrixChangedObservable.clear();
  22068. this.onProjectionMatrixChangedObservable.clear();
  22069. this.onAfterCheckInputsObservable.clear();
  22070. this.onRestoreStateObservable.clear();
  22071. // Inputs
  22072. if (this.inputs) {
  22073. this.inputs.clear();
  22074. }
  22075. // Animations
  22076. this.getScene().stopAnimation(this);
  22077. // Remove from scene
  22078. this.getScene().removeCamera(this);
  22079. while (this._rigCameras.length > 0) {
  22080. var camera = this._rigCameras.pop();
  22081. if (camera) {
  22082. camera.dispose();
  22083. }
  22084. }
  22085. // Postprocesses
  22086. if (this._rigPostProcess) {
  22087. this._rigPostProcess.dispose(this);
  22088. this._rigPostProcess = null;
  22089. this._postProcesses = [];
  22090. }
  22091. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22092. this._rigPostProcess = null;
  22093. this._postProcesses = [];
  22094. }
  22095. else {
  22096. var i = this._postProcesses.length;
  22097. while (--i >= 0) {
  22098. var postProcess = this._postProcesses[i];
  22099. if (postProcess) {
  22100. postProcess.dispose(this);
  22101. }
  22102. }
  22103. }
  22104. // Render targets
  22105. var i = this.customRenderTargets.length;
  22106. while (--i >= 0) {
  22107. this.customRenderTargets[i].dispose();
  22108. }
  22109. this.customRenderTargets = [];
  22110. // Active Meshes
  22111. this._activeMeshes.dispose();
  22112. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22113. };
  22114. Object.defineProperty(Camera.prototype, "leftCamera", {
  22115. // ---- Camera rigs section ----
  22116. get: function () {
  22117. if (this._rigCameras.length < 1) {
  22118. return null;
  22119. }
  22120. return this._rigCameras[0];
  22121. },
  22122. enumerable: true,
  22123. configurable: true
  22124. });
  22125. Object.defineProperty(Camera.prototype, "rightCamera", {
  22126. get: function () {
  22127. if (this._rigCameras.length < 2) {
  22128. return null;
  22129. }
  22130. return this._rigCameras[1];
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Camera.prototype.getLeftTarget = function () {
  22136. if (this._rigCameras.length < 1) {
  22137. return null;
  22138. }
  22139. return this._rigCameras[0].getTarget();
  22140. };
  22141. Camera.prototype.getRightTarget = function () {
  22142. if (this._rigCameras.length < 2) {
  22143. return null;
  22144. }
  22145. return this._rigCameras[1].getTarget();
  22146. };
  22147. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22148. if (this.cameraRigMode === mode) {
  22149. return;
  22150. }
  22151. while (this._rigCameras.length > 0) {
  22152. var camera = this._rigCameras.pop();
  22153. if (camera) {
  22154. camera.dispose();
  22155. }
  22156. }
  22157. this.cameraRigMode = mode;
  22158. this._cameraRigParams = {};
  22159. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22160. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22161. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22162. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22163. // create the rig cameras, unless none
  22164. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22165. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22166. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22167. if (leftCamera && rightCamera) {
  22168. this._rigCameras.push(leftCamera);
  22169. this._rigCameras.push(rightCamera);
  22170. }
  22171. }
  22172. switch (this.cameraRigMode) {
  22173. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22174. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22175. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22176. break;
  22177. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22178. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22179. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22180. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22181. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22182. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22183. break;
  22184. case Camera.RIG_MODE_VR:
  22185. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22186. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22187. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22188. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22189. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22190. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22191. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22192. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22193. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22194. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22195. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22196. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22197. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22198. if (metrics.compensateDistortion) {
  22199. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22200. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22201. }
  22202. break;
  22203. case Camera.RIG_MODE_WEBVR:
  22204. if (rigParams.vrDisplay) {
  22205. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22206. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22207. //Left eye
  22208. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22209. this._rigCameras[0].setCameraRigParameter("left", true);
  22210. //leaving this for future reference
  22211. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22212. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22213. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22214. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22215. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22216. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22217. this._rigCameras[0].parent = this;
  22218. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22219. //Right eye
  22220. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22221. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22222. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22223. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22224. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22225. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22226. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22227. this._rigCameras[1].parent = this;
  22228. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22229. if (Camera.UseAlternateWebVRRendering) {
  22230. this._rigCameras[1]._skipRendering = true;
  22231. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22232. }
  22233. }
  22234. break;
  22235. }
  22236. this._cascadePostProcessesToRigCams();
  22237. this.update();
  22238. };
  22239. Camera.prototype._getVRProjectionMatrix = function () {
  22240. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22241. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22242. return this._projectionMatrix;
  22243. };
  22244. Camera.prototype._updateCameraRotationMatrix = function () {
  22245. //Here for WebVR
  22246. };
  22247. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22248. //Here for WebVR
  22249. };
  22250. /**
  22251. * This function MUST be overwritten by the different WebVR cameras available.
  22252. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22253. */
  22254. Camera.prototype._getWebVRProjectionMatrix = function () {
  22255. return BABYLON.Matrix.Identity();
  22256. };
  22257. /**
  22258. * This function MUST be overwritten by the different WebVR cameras available.
  22259. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22260. */
  22261. Camera.prototype._getWebVRViewMatrix = function () {
  22262. return BABYLON.Matrix.Identity();
  22263. };
  22264. Camera.prototype.setCameraRigParameter = function (name, value) {
  22265. if (!this._cameraRigParams) {
  22266. this._cameraRigParams = {};
  22267. }
  22268. this._cameraRigParams[name] = value;
  22269. //provisionnally:
  22270. if (name === "interaxialDistance") {
  22271. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22272. }
  22273. };
  22274. /**
  22275. * needs to be overridden by children so sub has required properties to be copied
  22276. */
  22277. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22278. return null;
  22279. };
  22280. /**
  22281. * May need to be overridden by children
  22282. */
  22283. Camera.prototype._updateRigCameras = function () {
  22284. for (var i = 0; i < this._rigCameras.length; i++) {
  22285. this._rigCameras[i].minZ = this.minZ;
  22286. this._rigCameras[i].maxZ = this.maxZ;
  22287. this._rigCameras[i].fov = this.fov;
  22288. }
  22289. // only update viewport when ANAGLYPH
  22290. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22291. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22292. }
  22293. };
  22294. Camera.prototype._setupInputs = function () {
  22295. };
  22296. Camera.prototype.serialize = function () {
  22297. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22298. // Type
  22299. serializationObject.type = this.getClassName();
  22300. // Parent
  22301. if (this.parent) {
  22302. serializationObject.parentId = this.parent.id;
  22303. }
  22304. if (this.inputs) {
  22305. this.inputs.serialize(serializationObject);
  22306. }
  22307. // Animations
  22308. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22309. serializationObject.ranges = this.serializeAnimationRanges();
  22310. return serializationObject;
  22311. };
  22312. Camera.prototype.clone = function (name) {
  22313. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22314. };
  22315. Camera.prototype.getDirection = function (localAxis) {
  22316. var result = BABYLON.Vector3.Zero();
  22317. this.getDirectionToRef(localAxis, result);
  22318. return result;
  22319. };
  22320. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22321. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22322. };
  22323. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22324. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22325. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22326. switch (type) {
  22327. case "ArcRotateCamera":
  22328. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22329. case "DeviceOrientationCamera":
  22330. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22331. case "FollowCamera":
  22332. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22333. case "ArcFollowCamera":
  22334. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22335. case "GamepadCamera":
  22336. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22337. case "TouchCamera":
  22338. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22339. case "VirtualJoysticksCamera":
  22340. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22341. case "WebVRFreeCamera":
  22342. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22343. case "WebVRGamepadCamera":
  22344. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22345. case "VRDeviceOrientationFreeCamera":
  22346. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22347. case "VRDeviceOrientationGamepadCamera":
  22348. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22349. case "AnaglyphArcRotateCamera":
  22350. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22351. case "AnaglyphFreeCamera":
  22352. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22353. case "AnaglyphGamepadCamera":
  22354. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22355. case "AnaglyphUniversalCamera":
  22356. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22357. case "StereoscopicArcRotateCamera":
  22358. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22359. case "StereoscopicFreeCamera":
  22360. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22361. case "StereoscopicGamepadCamera":
  22362. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22363. case "StereoscopicUniversalCamera":
  22364. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22365. case "FreeCamera": // Forcing Universal here
  22366. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22367. default: // Universal Camera is the default value
  22368. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22369. }
  22370. };
  22371. Camera.prototype.computeWorldMatrix = function () {
  22372. return this.getWorldMatrix();
  22373. };
  22374. Camera.Parse = function (parsedCamera, scene) {
  22375. var type = parsedCamera.type;
  22376. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22377. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22378. // Parent
  22379. if (parsedCamera.parentId) {
  22380. camera._waitingParentId = parsedCamera.parentId;
  22381. }
  22382. //If camera has an input manager, let it parse inputs settings
  22383. if (camera.inputs) {
  22384. camera.inputs.parse(parsedCamera);
  22385. camera._setupInputs();
  22386. }
  22387. if (camera.setPosition) { // need to force position
  22388. camera.position.copyFromFloats(0, 0, 0);
  22389. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22390. }
  22391. // Target
  22392. if (parsedCamera.target) {
  22393. if (camera.setTarget) {
  22394. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22395. }
  22396. }
  22397. // Apply 3d rig, when found
  22398. if (parsedCamera.cameraRigMode) {
  22399. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22400. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22401. }
  22402. // Animations
  22403. if (parsedCamera.animations) {
  22404. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22405. var parsedAnimation = parsedCamera.animations[animationIndex];
  22406. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22407. }
  22408. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22409. }
  22410. if (parsedCamera.autoAnimate) {
  22411. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22412. }
  22413. return camera;
  22414. };
  22415. // Statics
  22416. Camera._PERSPECTIVE_CAMERA = 0;
  22417. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22418. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22419. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22420. Camera._RIG_MODE_NONE = 0;
  22421. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22422. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22423. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22424. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22425. Camera._RIG_MODE_VR = 20;
  22426. Camera._RIG_MODE_WEBVR = 21;
  22427. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22428. Camera.UseAlternateWebVRRendering = false;
  22429. __decorate([
  22430. BABYLON.serializeAsVector3()
  22431. ], Camera.prototype, "position", void 0);
  22432. __decorate([
  22433. BABYLON.serializeAsVector3()
  22434. ], Camera.prototype, "upVector", void 0);
  22435. __decorate([
  22436. BABYLON.serialize()
  22437. ], Camera.prototype, "orthoLeft", void 0);
  22438. __decorate([
  22439. BABYLON.serialize()
  22440. ], Camera.prototype, "orthoRight", void 0);
  22441. __decorate([
  22442. BABYLON.serialize()
  22443. ], Camera.prototype, "orthoBottom", void 0);
  22444. __decorate([
  22445. BABYLON.serialize()
  22446. ], Camera.prototype, "orthoTop", void 0);
  22447. __decorate([
  22448. BABYLON.serialize()
  22449. ], Camera.prototype, "fov", void 0);
  22450. __decorate([
  22451. BABYLON.serialize()
  22452. ], Camera.prototype, "minZ", void 0);
  22453. __decorate([
  22454. BABYLON.serialize()
  22455. ], Camera.prototype, "maxZ", void 0);
  22456. __decorate([
  22457. BABYLON.serialize()
  22458. ], Camera.prototype, "inertia", void 0);
  22459. __decorate([
  22460. BABYLON.serialize()
  22461. ], Camera.prototype, "mode", void 0);
  22462. __decorate([
  22463. BABYLON.serialize()
  22464. ], Camera.prototype, "layerMask", void 0);
  22465. __decorate([
  22466. BABYLON.serialize()
  22467. ], Camera.prototype, "fovMode", void 0);
  22468. __decorate([
  22469. BABYLON.serialize()
  22470. ], Camera.prototype, "cameraRigMode", void 0);
  22471. __decorate([
  22472. BABYLON.serialize()
  22473. ], Camera.prototype, "interaxialDistance", void 0);
  22474. __decorate([
  22475. BABYLON.serialize()
  22476. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22477. return Camera;
  22478. }(BABYLON.Node));
  22479. BABYLON.Camera = Camera;
  22480. })(BABYLON || (BABYLON = {}));
  22481. //# sourceMappingURL=babylon.camera.js.map
  22482. var BABYLON;
  22483. (function (BABYLON) {
  22484. var RenderingManager = /** @class */ (function () {
  22485. function RenderingManager(scene) {
  22486. this._renderingGroups = new Array();
  22487. this._autoClearDepthStencil = {};
  22488. this._customOpaqueSortCompareFn = {};
  22489. this._customAlphaTestSortCompareFn = {};
  22490. this._customTransparentSortCompareFn = {};
  22491. this._renderinGroupInfo = null;
  22492. this._scene = scene;
  22493. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22494. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22495. }
  22496. }
  22497. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22498. if (depth === void 0) { depth = true; }
  22499. if (stencil === void 0) { stencil = true; }
  22500. if (this._depthStencilBufferAlreadyCleaned) {
  22501. return;
  22502. }
  22503. this._scene.getEngine().clear(null, false, depth, stencil);
  22504. this._depthStencilBufferAlreadyCleaned = true;
  22505. };
  22506. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22507. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22508. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22509. var info = null;
  22510. if (observable) {
  22511. if (!this._renderinGroupInfo) {
  22512. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22513. }
  22514. info = this._renderinGroupInfo;
  22515. info.scene = this._scene;
  22516. info.camera = this._scene.activeCamera;
  22517. }
  22518. // Dispatch sprites
  22519. if (renderSprites) {
  22520. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22521. var manager = this._scene.spriteManagers[index];
  22522. this.dispatchSprites(manager);
  22523. }
  22524. }
  22525. // Render
  22526. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22527. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22528. var renderingGroup = this._renderingGroups[index];
  22529. if (!renderingGroup && !observable)
  22530. continue;
  22531. var renderingGroupMask = 0;
  22532. // Fire PRECLEAR stage
  22533. if (observable && info) {
  22534. renderingGroupMask = Math.pow(2, index);
  22535. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22536. info.renderingGroupId = index;
  22537. observable.notifyObservers(info, renderingGroupMask);
  22538. }
  22539. // Clear depth/stencil if needed
  22540. if (RenderingManager.AUTOCLEAR) {
  22541. var autoClear = this._autoClearDepthStencil[index];
  22542. if (autoClear && autoClear.autoClear) {
  22543. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22544. }
  22545. }
  22546. if (observable && info) {
  22547. // Fire PREOPAQUE stage
  22548. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22549. observable.notifyObservers(info, renderingGroupMask);
  22550. // Fire PRETRANSPARENT stage
  22551. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22552. observable.notifyObservers(info, renderingGroupMask);
  22553. }
  22554. if (renderingGroup)
  22555. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22556. // Fire POSTTRANSPARENT stage
  22557. if (observable && info) {
  22558. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22559. observable.notifyObservers(info, renderingGroupMask);
  22560. }
  22561. }
  22562. };
  22563. RenderingManager.prototype.reset = function () {
  22564. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22565. var renderingGroup = this._renderingGroups[index];
  22566. if (renderingGroup) {
  22567. renderingGroup.prepare();
  22568. }
  22569. }
  22570. };
  22571. RenderingManager.prototype.dispose = function () {
  22572. this.freeRenderingGroups();
  22573. this._renderingGroups.length = 0;
  22574. };
  22575. /**
  22576. * Clear the info related to rendering groups preventing retention points during dispose.
  22577. */
  22578. RenderingManager.prototype.freeRenderingGroups = function () {
  22579. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22580. var renderingGroup = this._renderingGroups[index];
  22581. if (renderingGroup) {
  22582. renderingGroup.dispose();
  22583. }
  22584. }
  22585. };
  22586. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22587. if (this._renderingGroups[renderingGroupId] === undefined) {
  22588. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22589. }
  22590. };
  22591. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22592. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22593. this._prepareRenderingGroup(renderingGroupId);
  22594. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22595. };
  22596. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22597. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22598. this._prepareRenderingGroup(renderingGroupId);
  22599. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22600. };
  22601. /**
  22602. * @param subMesh The submesh to dispatch
  22603. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22604. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22605. */
  22606. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22607. if (mesh === undefined) {
  22608. mesh = subMesh.getMesh();
  22609. }
  22610. var renderingGroupId = mesh.renderingGroupId || 0;
  22611. this._prepareRenderingGroup(renderingGroupId);
  22612. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22613. };
  22614. /**
  22615. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22616. * This allowed control for front to back rendering or reversly depending of the special needs.
  22617. *
  22618. * @param renderingGroupId The rendering group id corresponding to its index
  22619. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22620. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22621. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22622. */
  22623. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22624. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22625. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22626. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22627. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22628. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22629. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22630. if (this._renderingGroups[renderingGroupId]) {
  22631. var group = this._renderingGroups[renderingGroupId];
  22632. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22633. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22634. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22635. }
  22636. };
  22637. /**
  22638. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22639. *
  22640. * @param renderingGroupId The rendering group id corresponding to its index
  22641. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22642. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22643. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22644. */
  22645. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22646. if (depth === void 0) { depth = true; }
  22647. if (stencil === void 0) { stencil = true; }
  22648. this._autoClearDepthStencil[renderingGroupId] = {
  22649. autoClear: autoClearDepthStencil,
  22650. depth: depth,
  22651. stencil: stencil
  22652. };
  22653. };
  22654. /**
  22655. * The max id used for rendering groups (not included)
  22656. */
  22657. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22658. /**
  22659. * The min id used for rendering groups (included)
  22660. */
  22661. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22662. /**
  22663. * Used to globally prevent autoclearing scenes.
  22664. */
  22665. RenderingManager.AUTOCLEAR = true;
  22666. return RenderingManager;
  22667. }());
  22668. BABYLON.RenderingManager = RenderingManager;
  22669. })(BABYLON || (BABYLON = {}));
  22670. //# sourceMappingURL=babylon.renderingManager.js.map
  22671. var BABYLON;
  22672. (function (BABYLON) {
  22673. var RenderingGroup = /** @class */ (function () {
  22674. /**
  22675. * Creates a new rendering group.
  22676. * @param index The rendering group index
  22677. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22678. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22679. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22680. */
  22681. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22682. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22683. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22684. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22685. this.index = index;
  22686. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22687. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22688. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22689. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22690. this._particleSystems = new BABYLON.SmartArray(256);
  22691. this._spriteManagers = new BABYLON.SmartArray(256);
  22692. this._edgesRenderers = new BABYLON.SmartArray(16);
  22693. this._scene = scene;
  22694. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22695. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22696. this.transparentSortCompareFn = transparentSortCompareFn;
  22697. }
  22698. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22699. /**
  22700. * Set the opaque sort comparison function.
  22701. * If null the sub meshes will be render in the order they were created
  22702. */
  22703. set: function (value) {
  22704. this._opaqueSortCompareFn = value;
  22705. if (value) {
  22706. this._renderOpaque = this.renderOpaqueSorted;
  22707. }
  22708. else {
  22709. this._renderOpaque = RenderingGroup.renderUnsorted;
  22710. }
  22711. },
  22712. enumerable: true,
  22713. configurable: true
  22714. });
  22715. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22716. /**
  22717. * Set the alpha test sort comparison function.
  22718. * If null the sub meshes will be render in the order they were created
  22719. */
  22720. set: function (value) {
  22721. this._alphaTestSortCompareFn = value;
  22722. if (value) {
  22723. this._renderAlphaTest = this.renderAlphaTestSorted;
  22724. }
  22725. else {
  22726. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22727. }
  22728. },
  22729. enumerable: true,
  22730. configurable: true
  22731. });
  22732. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22733. /**
  22734. * Set the transparent sort comparison function.
  22735. * If null the sub meshes will be render in the order they were created
  22736. */
  22737. set: function (value) {
  22738. if (value) {
  22739. this._transparentSortCompareFn = value;
  22740. }
  22741. else {
  22742. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22743. }
  22744. this._renderTransparent = this.renderTransparentSorted;
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. /**
  22750. * Render all the sub meshes contained in the group.
  22751. * @param customRenderFunction Used to override the default render behaviour of the group.
  22752. * @returns true if rendered some submeshes.
  22753. */
  22754. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22755. if (customRenderFunction) {
  22756. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22757. return;
  22758. }
  22759. var engine = this._scene.getEngine();
  22760. // Depth only
  22761. if (this._depthOnlySubMeshes.length !== 0) {
  22762. engine.setColorWrite(false);
  22763. this._renderAlphaTest(this._depthOnlySubMeshes);
  22764. engine.setColorWrite(true);
  22765. }
  22766. // Opaque
  22767. if (this._opaqueSubMeshes.length !== 0) {
  22768. this._renderOpaque(this._opaqueSubMeshes);
  22769. }
  22770. // Alpha test
  22771. if (this._alphaTestSubMeshes.length !== 0) {
  22772. this._renderAlphaTest(this._alphaTestSubMeshes);
  22773. }
  22774. var stencilState = engine.getStencilBuffer();
  22775. engine.setStencilBuffer(false);
  22776. // Sprites
  22777. if (renderSprites) {
  22778. this._renderSprites();
  22779. }
  22780. // Particles
  22781. if (renderParticles) {
  22782. this._renderParticles(activeMeshes);
  22783. }
  22784. if (this.onBeforeTransparentRendering) {
  22785. this.onBeforeTransparentRendering();
  22786. }
  22787. // Transparent
  22788. if (this._transparentSubMeshes.length !== 0) {
  22789. this._renderTransparent(this._transparentSubMeshes);
  22790. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22791. }
  22792. // Set back stencil to false in case it changes before the edge renderer.
  22793. engine.setStencilBuffer(false);
  22794. // Edges
  22795. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22796. this._edgesRenderers.data[edgesRendererIndex].render();
  22797. }
  22798. // Restore Stencil state.
  22799. engine.setStencilBuffer(stencilState);
  22800. };
  22801. /**
  22802. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22803. * @param subMeshes The submeshes to render
  22804. */
  22805. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22806. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22807. };
  22808. /**
  22809. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22810. * @param subMeshes The submeshes to render
  22811. */
  22812. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22813. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22814. };
  22815. /**
  22816. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22817. * @param subMeshes The submeshes to render
  22818. */
  22819. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22820. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22821. };
  22822. /**
  22823. * Renders the submeshes in a specified order.
  22824. * @param subMeshes The submeshes to sort before render
  22825. * @param sortCompareFn The comparison function use to sort
  22826. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22827. * @param transparent Specifies to activate blending if true
  22828. */
  22829. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22830. var subIndex = 0;
  22831. var subMesh;
  22832. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22833. for (; subIndex < subMeshes.length; subIndex++) {
  22834. subMesh = subMeshes.data[subIndex];
  22835. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22836. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22837. }
  22838. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22839. if (sortCompareFn) {
  22840. sortedArray.sort(sortCompareFn);
  22841. }
  22842. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22843. subMesh = sortedArray[subIndex];
  22844. if (transparent) {
  22845. var material = subMesh.getMaterial();
  22846. if (material && material.needDepthPrePass) {
  22847. var engine = material.getScene().getEngine();
  22848. engine.setColorWrite(false);
  22849. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22850. subMesh.render(false);
  22851. engine.setColorWrite(true);
  22852. }
  22853. }
  22854. subMesh.render(transparent);
  22855. }
  22856. };
  22857. /**
  22858. * Renders the submeshes in the order they were dispatched (no sort applied).
  22859. * @param subMeshes The submeshes to render
  22860. */
  22861. RenderingGroup.renderUnsorted = function (subMeshes) {
  22862. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22863. var submesh = subMeshes.data[subIndex];
  22864. submesh.render(false);
  22865. }
  22866. };
  22867. /**
  22868. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22869. * are rendered back to front if in the same alpha index.
  22870. *
  22871. * @param a The first submesh
  22872. * @param b The second submesh
  22873. * @returns The result of the comparison
  22874. */
  22875. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22876. // Alpha index first
  22877. if (a._alphaIndex > b._alphaIndex) {
  22878. return 1;
  22879. }
  22880. if (a._alphaIndex < b._alphaIndex) {
  22881. return -1;
  22882. }
  22883. // Then distance to camera
  22884. return RenderingGroup.backToFrontSortCompare(a, b);
  22885. };
  22886. /**
  22887. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22888. * are rendered back to front.
  22889. *
  22890. * @param a The first submesh
  22891. * @param b The second submesh
  22892. * @returns The result of the comparison
  22893. */
  22894. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22895. // Then distance to camera
  22896. if (a._distanceToCamera < b._distanceToCamera) {
  22897. return 1;
  22898. }
  22899. if (a._distanceToCamera > b._distanceToCamera) {
  22900. return -1;
  22901. }
  22902. return 0;
  22903. };
  22904. /**
  22905. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22906. * are rendered front to back (prevent overdraw).
  22907. *
  22908. * @param a The first submesh
  22909. * @param b The second submesh
  22910. * @returns The result of the comparison
  22911. */
  22912. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22913. // Then distance to camera
  22914. if (a._distanceToCamera < b._distanceToCamera) {
  22915. return -1;
  22916. }
  22917. if (a._distanceToCamera > b._distanceToCamera) {
  22918. return 1;
  22919. }
  22920. return 0;
  22921. };
  22922. /**
  22923. * Resets the different lists of submeshes to prepare a new frame.
  22924. */
  22925. RenderingGroup.prototype.prepare = function () {
  22926. this._opaqueSubMeshes.reset();
  22927. this._transparentSubMeshes.reset();
  22928. this._alphaTestSubMeshes.reset();
  22929. this._depthOnlySubMeshes.reset();
  22930. this._particleSystems.reset();
  22931. this._spriteManagers.reset();
  22932. this._edgesRenderers.reset();
  22933. };
  22934. RenderingGroup.prototype.dispose = function () {
  22935. this._opaqueSubMeshes.dispose();
  22936. this._transparentSubMeshes.dispose();
  22937. this._alphaTestSubMeshes.dispose();
  22938. this._depthOnlySubMeshes.dispose();
  22939. this._particleSystems.dispose();
  22940. this._spriteManagers.dispose();
  22941. this._edgesRenderers.dispose();
  22942. };
  22943. /**
  22944. * Inserts the submesh in its correct queue depending on its material.
  22945. * @param subMesh The submesh to dispatch
  22946. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22947. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22948. */
  22949. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22950. // Get mesh and materials if not provided
  22951. if (mesh === undefined) {
  22952. mesh = subMesh.getMesh();
  22953. }
  22954. if (material === undefined) {
  22955. material = subMesh.getMaterial();
  22956. }
  22957. if (material === null || material === undefined) {
  22958. return;
  22959. }
  22960. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  22961. this._transparentSubMeshes.push(subMesh);
  22962. }
  22963. else if (material.needAlphaTesting()) { // Alpha test
  22964. if (material.needDepthPrePass) {
  22965. this._depthOnlySubMeshes.push(subMesh);
  22966. }
  22967. this._alphaTestSubMeshes.push(subMesh);
  22968. }
  22969. else {
  22970. if (material.needDepthPrePass) {
  22971. this._depthOnlySubMeshes.push(subMesh);
  22972. }
  22973. this._opaqueSubMeshes.push(subMesh); // Opaque
  22974. }
  22975. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22976. this._edgesRenderers.push(mesh._edgesRenderer);
  22977. }
  22978. };
  22979. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22980. this._spriteManagers.push(spriteManager);
  22981. };
  22982. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22983. this._particleSystems.push(particleSystem);
  22984. };
  22985. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22986. if (this._particleSystems.length === 0) {
  22987. return;
  22988. }
  22989. // Particles
  22990. var activeCamera = this._scene.activeCamera;
  22991. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22992. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22993. var particleSystem = this._particleSystems.data[particleIndex];
  22994. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22995. continue;
  22996. }
  22997. var emitter = particleSystem.emitter;
  22998. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22999. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23000. }
  23001. }
  23002. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23003. };
  23004. RenderingGroup.prototype._renderSprites = function () {
  23005. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23006. return;
  23007. }
  23008. // Sprites
  23009. var activeCamera = this._scene.activeCamera;
  23010. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23011. for (var id = 0; id < this._spriteManagers.length; id++) {
  23012. var spriteManager = this._spriteManagers.data[id];
  23013. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23014. spriteManager.render();
  23015. }
  23016. }
  23017. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23018. };
  23019. return RenderingGroup;
  23020. }());
  23021. BABYLON.RenderingGroup = RenderingGroup;
  23022. })(BABYLON || (BABYLON = {}));
  23023. //# sourceMappingURL=babylon.renderingGroup.js.map
  23024. var BABYLON;
  23025. (function (BABYLON) {
  23026. /** @ignore */
  23027. var ClickInfo = /** @class */ (function () {
  23028. function ClickInfo() {
  23029. this._singleClick = false;
  23030. this._doubleClick = false;
  23031. this._hasSwiped = false;
  23032. this._ignore = false;
  23033. }
  23034. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23035. get: function () {
  23036. return this._singleClick;
  23037. },
  23038. set: function (b) {
  23039. this._singleClick = b;
  23040. },
  23041. enumerable: true,
  23042. configurable: true
  23043. });
  23044. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23045. get: function () {
  23046. return this._doubleClick;
  23047. },
  23048. set: function (b) {
  23049. this._doubleClick = b;
  23050. },
  23051. enumerable: true,
  23052. configurable: true
  23053. });
  23054. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23055. get: function () {
  23056. return this._hasSwiped;
  23057. },
  23058. set: function (b) {
  23059. this._hasSwiped = b;
  23060. },
  23061. enumerable: true,
  23062. configurable: true
  23063. });
  23064. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23065. get: function () {
  23066. return this._ignore;
  23067. },
  23068. set: function (b) {
  23069. this._ignore = b;
  23070. },
  23071. enumerable: true,
  23072. configurable: true
  23073. });
  23074. return ClickInfo;
  23075. }());
  23076. /**
  23077. * This class is used by the onRenderingGroupObservable
  23078. */
  23079. var RenderingGroupInfo = /** @class */ (function () {
  23080. function RenderingGroupInfo() {
  23081. }
  23082. /**
  23083. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23084. * This stage will be fired no matter what
  23085. */
  23086. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23087. /**
  23088. * Called before opaque object are rendered.
  23089. * This stage will be fired only if there's 3D Opaque content to render
  23090. */
  23091. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23092. /**
  23093. * Called after the opaque objects are rendered and before the transparent ones
  23094. * This stage will be fired only if there's 3D transparent content to render
  23095. */
  23096. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23097. /**
  23098. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23099. * This stage will be fired no matter what
  23100. */
  23101. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23102. return RenderingGroupInfo;
  23103. }());
  23104. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23105. /**
  23106. * Represents a scene to be rendered by the engine.
  23107. * @see http://doc.babylonjs.com/features/scene
  23108. */
  23109. var Scene = /** @class */ (function () {
  23110. /**
  23111. * Creates a new Scene
  23112. * @param engine defines the engine to use to render this scene
  23113. */
  23114. function Scene(engine) {
  23115. // Members
  23116. /**
  23117. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23118. */
  23119. this.autoClear = true;
  23120. /**
  23121. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23122. */
  23123. this.autoClearDepthAndStencil = true;
  23124. /**
  23125. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23126. */
  23127. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23128. /**
  23129. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23130. */
  23131. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23132. this._forceWireframe = false;
  23133. this._forcePointsCloud = false;
  23134. /**
  23135. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23136. */
  23137. this.forceShowBoundingBoxes = false;
  23138. /**
  23139. * Gets or sets a boolean indicating if animations are enabled
  23140. */
  23141. this.animationsEnabled = true;
  23142. this._animationPropertiesOverride = null;
  23143. /**
  23144. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23145. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23146. */
  23147. this.useConstantAnimationDeltaTime = false;
  23148. /**
  23149. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23150. * Please note that it requires to run a ray cast through the scene on every frame
  23151. */
  23152. this.constantlyUpdateMeshUnderPointer = false;
  23153. /**
  23154. * Defines the HTML cursor to use when hovering over interactive elements
  23155. */
  23156. this.hoverCursor = "pointer";
  23157. /**
  23158. * Defines the HTML default cursor to use (empty by default)
  23159. */
  23160. this.defaultCursor = "";
  23161. /**
  23162. * This is used to call preventDefault() on pointer down
  23163. * in order to block unwanted artifacts like system double clicks
  23164. */
  23165. this.preventDefaultOnPointerDown = true;
  23166. // Metadata
  23167. /**
  23168. * Gets or sets user defined metadata
  23169. */
  23170. this.metadata = null;
  23171. /**
  23172. * Use this array to add regular expressions used to disable offline support for specific urls
  23173. */
  23174. this.disableOfflineSupportExceptionRules = new Array();
  23175. /**
  23176. * An event triggered when the scene is disposed.
  23177. */
  23178. this.onDisposeObservable = new BABYLON.Observable();
  23179. this._onDisposeObserver = null;
  23180. /**
  23181. * An event triggered before rendering the scene (right after animations and physics)
  23182. */
  23183. this.onBeforeRenderObservable = new BABYLON.Observable();
  23184. this._onBeforeRenderObserver = null;
  23185. /**
  23186. * An event triggered after rendering the scene
  23187. */
  23188. this.onAfterRenderObservable = new BABYLON.Observable();
  23189. this._onAfterRenderObserver = null;
  23190. /**
  23191. * An event triggered before animating the scene
  23192. */
  23193. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23194. /**
  23195. * An event triggered after animations processing
  23196. */
  23197. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23198. /**
  23199. * An event triggered before draw calls are ready to be sent
  23200. */
  23201. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23202. /**
  23203. * An event triggered after draw calls have been sent
  23204. */
  23205. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23206. /**
  23207. * An event triggered when physic simulation is about to be run
  23208. */
  23209. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23210. /**
  23211. * An event triggered when physic simulation has been done
  23212. */
  23213. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23214. /**
  23215. * An event triggered when the scene is ready
  23216. */
  23217. this.onReadyObservable = new BABYLON.Observable();
  23218. /**
  23219. * An event triggered before rendering a camera
  23220. */
  23221. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23222. this._onBeforeCameraRenderObserver = null;
  23223. /**
  23224. * An event triggered after rendering a camera
  23225. */
  23226. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23227. this._onAfterCameraRenderObserver = null;
  23228. /**
  23229. * An event triggered when active meshes evaluation is about to start
  23230. */
  23231. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23232. /**
  23233. * An event triggered when active meshes evaluation is done
  23234. */
  23235. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23236. /**
  23237. * An event triggered when particles rendering is about to start
  23238. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23239. */
  23240. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23241. /**
  23242. * An event triggered when particles rendering is done
  23243. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23244. */
  23245. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23246. /**
  23247. * An event triggered when sprites rendering is about to start
  23248. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23249. */
  23250. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23251. /**
  23252. * An event triggered when sprites rendering is done
  23253. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23254. */
  23255. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23256. /**
  23257. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23258. */
  23259. this.onDataLoadedObservable = new BABYLON.Observable();
  23260. /**
  23261. * An event triggered when a camera is created
  23262. */
  23263. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23264. /**
  23265. * An event triggered when a camera is removed
  23266. */
  23267. this.onCameraRemovedObservable = new BABYLON.Observable();
  23268. /**
  23269. * An event triggered when a light is created
  23270. */
  23271. this.onNewLightAddedObservable = new BABYLON.Observable();
  23272. /**
  23273. * An event triggered when a light is removed
  23274. */
  23275. this.onLightRemovedObservable = new BABYLON.Observable();
  23276. /**
  23277. * An event triggered when a geometry is created
  23278. */
  23279. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23280. /**
  23281. * An event triggered when a geometry is removed
  23282. */
  23283. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23284. /**
  23285. * An event triggered when a transform node is created
  23286. */
  23287. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23288. /**
  23289. * An event triggered when a transform node is removed
  23290. */
  23291. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23292. /**
  23293. * An event triggered when a mesh is created
  23294. */
  23295. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23296. /**
  23297. * An event triggered when a mesh is removed
  23298. */
  23299. this.onMeshRemovedObservable = new BABYLON.Observable();
  23300. /**
  23301. * An event triggered when render targets are about to be rendered
  23302. * Can happen multiple times per frame.
  23303. */
  23304. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23305. /**
  23306. * An event triggered when render targets were rendered.
  23307. * Can happen multiple times per frame.
  23308. */
  23309. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23310. /**
  23311. * An event triggered before calculating deterministic simulation step
  23312. */
  23313. this.onBeforeStepObservable = new BABYLON.Observable();
  23314. /**
  23315. * An event triggered after calculating deterministic simulation step
  23316. */
  23317. this.onAfterStepObservable = new BABYLON.Observable();
  23318. /**
  23319. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23320. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23321. * 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)
  23322. */
  23323. this.onRenderingGroupObservable = new BABYLON.Observable();
  23324. // Animations
  23325. /**
  23326. * Gets a list of Animations associated with the scene
  23327. */
  23328. this.animations = [];
  23329. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23330. /**
  23331. * 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).
  23332. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23333. */
  23334. this.onPrePointerObservable = new BABYLON.Observable();
  23335. /**
  23336. * Observable event triggered each time an input event is received from the rendering canvas
  23337. */
  23338. this.onPointerObservable = new BABYLON.Observable();
  23339. this._meshPickProceed = false;
  23340. this._currentPickResult = null;
  23341. this._previousPickResult = null;
  23342. this._totalPointersPressed = 0;
  23343. this._doubleClickOccured = false;
  23344. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23345. this.cameraToUseForPointers = null;
  23346. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23347. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23348. this._startingPointerTime = 0;
  23349. this._previousStartingPointerTime = 0;
  23350. // Deterministic lockstep
  23351. this._timeAccumulator = 0;
  23352. this._currentStepId = 0;
  23353. this._currentInternalStep = 0;
  23354. // Keyboard
  23355. /**
  23356. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23357. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23358. */
  23359. this.onPreKeyboardObservable = new BABYLON.Observable();
  23360. /**
  23361. * Observable event triggered each time an keyboard event is received from the hosting window
  23362. */
  23363. this.onKeyboardObservable = new BABYLON.Observable();
  23364. // Coordinates system
  23365. this._useRightHandedSystem = false;
  23366. // Fog
  23367. this._fogEnabled = true;
  23368. this._fogMode = Scene.FOGMODE_NONE;
  23369. /**
  23370. * Gets or sets the fog color to use
  23371. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23372. */
  23373. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23374. /**
  23375. * Gets or sets the fog density to use
  23376. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23377. */
  23378. this.fogDensity = 0.1;
  23379. /**
  23380. * Gets or sets the fog start distance to use
  23381. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23382. */
  23383. this.fogStart = 0;
  23384. /**
  23385. * Gets or sets the fog end distance to use
  23386. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23387. */
  23388. this.fogEnd = 1000.0;
  23389. // Lights
  23390. this._shadowsEnabled = true;
  23391. this._lightsEnabled = true;
  23392. /**
  23393. * All of the lights added to this scene
  23394. * @see http://doc.babylonjs.com/babylon101/lights
  23395. */
  23396. this.lights = new Array();
  23397. // Cameras
  23398. /** All of the cameras added to this scene.
  23399. * @see http://doc.babylonjs.com/babylon101/cameras
  23400. */
  23401. this.cameras = new Array();
  23402. /** All of the active cameras added to this scene. */
  23403. this.activeCameras = new Array();
  23404. // Meshes
  23405. /**
  23406. * All of the tranform nodes added to this scene
  23407. * @see http://doc.babylonjs.com/how_to/transformnode
  23408. */
  23409. this.transformNodes = new Array();
  23410. /**
  23411. * All of the (abstract) meshes added to this scene
  23412. */
  23413. this.meshes = new Array();
  23414. /**
  23415. * All of the animation groups added to this scene
  23416. * @see http://doc.babylonjs.com/how_to/group
  23417. */
  23418. this.animationGroups = new Array();
  23419. // Geometries
  23420. this._geometries = new Array();
  23421. /**
  23422. * All of the materials added to this scene
  23423. * @see http://doc.babylonjs.com/babylon101/materials
  23424. */
  23425. this.materials = new Array();
  23426. /**
  23427. * All of the multi-materials added to this scene
  23428. * @see http://doc.babylonjs.com/how_to/multi_materials
  23429. */
  23430. this.multiMaterials = new Array();
  23431. // Textures
  23432. this._texturesEnabled = true;
  23433. /**
  23434. * All of the textures added to this scene
  23435. */
  23436. this.textures = new Array();
  23437. // Particles
  23438. /**
  23439. * Gets or sets a boolean indicating if particles are enabled on this scene
  23440. */
  23441. this.particlesEnabled = true;
  23442. /**
  23443. * All of the particle systems added to this scene
  23444. * @see http://doc.babylonjs.com/babylon101/particles
  23445. */
  23446. this.particleSystems = new Array();
  23447. // Sprites
  23448. /**
  23449. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23450. */
  23451. this.spritesEnabled = true;
  23452. /**
  23453. * All of the sprite managers added to this scene
  23454. * @see http://doc.babylonjs.com/babylon101/sprites
  23455. */
  23456. this.spriteManagers = new Array();
  23457. /**
  23458. * The list of layers (background and foreground) of the scene
  23459. */
  23460. this.layers = new Array();
  23461. /**
  23462. * The list of effect layers (highlights/glow) added to the scene
  23463. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23464. * @see http://doc.babylonjs.com/how_to/glow_layer
  23465. */
  23466. this.effectLayers = new Array();
  23467. // Skeletons
  23468. this._skeletonsEnabled = true;
  23469. /**
  23470. * The list of skeletons added to the scene
  23471. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23472. */
  23473. this.skeletons = new Array();
  23474. // Morph targets
  23475. /**
  23476. * The list of morph target managers added to the scene
  23477. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23478. */
  23479. this.morphTargetManagers = new Array();
  23480. // Lens flares
  23481. /**
  23482. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23483. */
  23484. this.lensFlaresEnabled = true;
  23485. /**
  23486. * The list of lens flare system added to the scene
  23487. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23488. */
  23489. this.lensFlareSystems = new Array();
  23490. // Collisions
  23491. /**
  23492. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23493. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23494. */
  23495. this.collisionsEnabled = true;
  23496. /**
  23497. * Defines the gravity applied to this scene (used only for collisions)
  23498. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23499. */
  23500. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23501. // Postprocesses
  23502. /**
  23503. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23504. */
  23505. this.postProcessesEnabled = true;
  23506. /**
  23507. * The list of postprocesses added to the scene
  23508. */
  23509. this.postProcesses = new Array();
  23510. // Customs render targets
  23511. /**
  23512. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23513. */
  23514. this.renderTargetsEnabled = true;
  23515. /**
  23516. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23517. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23518. */
  23519. this.dumpNextRenderTargets = false;
  23520. /**
  23521. * The list of user defined render targets added to the scene
  23522. */
  23523. this.customRenderTargets = new Array();
  23524. /**
  23525. * Gets the list of meshes imported to the scene through SceneLoader
  23526. */
  23527. this.importedMeshesFiles = new Array();
  23528. // Probes
  23529. /**
  23530. * Gets or sets a boolean indicating if probes are enabled on this scene
  23531. */
  23532. this.probesEnabled = true;
  23533. /**
  23534. * The list of reflection probes added to the scene
  23535. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23536. */
  23537. this.reflectionProbes = new Array();
  23538. /** @ignore */
  23539. this._actionManagers = new Array();
  23540. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23541. // Procedural textures
  23542. /**
  23543. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23544. */
  23545. this.proceduralTexturesEnabled = true;
  23546. /**
  23547. * The list of procedural textures added to the scene
  23548. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23549. */
  23550. this.proceduralTextures = new Array();
  23551. /**
  23552. * The list of sound tracks added to the scene
  23553. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23554. */
  23555. this.soundTracks = new Array();
  23556. this._audioEnabled = true;
  23557. this._headphone = false;
  23558. // Performance counters
  23559. this._totalVertices = new BABYLON.PerfCounter();
  23560. /** @ignore */
  23561. this._activeIndices = new BABYLON.PerfCounter();
  23562. /** @ignore */
  23563. this._activeParticles = new BABYLON.PerfCounter();
  23564. /** @ignore */
  23565. this._activeBones = new BABYLON.PerfCounter();
  23566. this._animationTime = 0;
  23567. /**
  23568. * Gets or sets a general scale for animation speed
  23569. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23570. */
  23571. this.animationTimeScale = 1;
  23572. this._renderId = 0;
  23573. this._executeWhenReadyTimeoutId = -1;
  23574. this._intermediateRendering = false;
  23575. this._viewUpdateFlag = -1;
  23576. this._projectionUpdateFlag = -1;
  23577. this._alternateViewUpdateFlag = -1;
  23578. this._alternateProjectionUpdateFlag = -1;
  23579. /** @ignore */
  23580. this._toBeDisposed = new BABYLON.SmartArray(256);
  23581. this._activeRequests = new Array();
  23582. this._pendingData = new Array();
  23583. this._isDisposed = false;
  23584. /**
  23585. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23586. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23587. */
  23588. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23589. this._activeMeshes = new BABYLON.SmartArray(256);
  23590. this._processedMaterials = new BABYLON.SmartArray(256);
  23591. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23592. /** @ignore */
  23593. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23594. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23595. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23596. /** @ignore */
  23597. this._activeAnimatables = new Array();
  23598. this._transformMatrix = BABYLON.Matrix.Zero();
  23599. this._useAlternateCameraConfiguration = false;
  23600. this._alternateRendering = false;
  23601. /**
  23602. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23603. * This is useful if there are more lights that the maximum simulteanous authorized
  23604. */
  23605. this.requireLightSorting = false;
  23606. this._depthRenderer = {};
  23607. this._activeMeshesFrozen = false;
  23608. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23609. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23610. this._engine.scenes.push(this);
  23611. this._uid = null;
  23612. this._renderingManager = new BABYLON.RenderingManager(this);
  23613. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23614. if (BABYLON.OutlineRenderer) {
  23615. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23616. }
  23617. if (BABYLON.Tools.IsWindowObjectExist()) {
  23618. this.attachControl();
  23619. }
  23620. //simplification queue
  23621. if (BABYLON.SimplificationQueue) {
  23622. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23623. }
  23624. //collision coordinator initialization. For now legacy per default.
  23625. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23626. // Uniform Buffer
  23627. this._createUbo();
  23628. // Default Image processing definition.
  23629. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23630. }
  23631. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23632. /** The fog is deactivated */
  23633. get: function () {
  23634. return Scene._FOGMODE_NONE;
  23635. },
  23636. enumerable: true,
  23637. configurable: true
  23638. });
  23639. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23640. /** The fog density is following an exponential function */
  23641. get: function () {
  23642. return Scene._FOGMODE_EXP;
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23648. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23649. get: function () {
  23650. return Scene._FOGMODE_EXP2;
  23651. },
  23652. enumerable: true,
  23653. configurable: true
  23654. });
  23655. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23656. /** The fog density is following a linear function. */
  23657. get: function () {
  23658. return Scene._FOGMODE_LINEAR;
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23664. /**
  23665. * Texture used in all pbr material as the reflection texture.
  23666. * As in the majority of the scene they are the same (exception for multi room and so on),
  23667. * this is easier to reference from here than from all the materials.
  23668. */
  23669. get: function () {
  23670. return this._environmentTexture;
  23671. },
  23672. /**
  23673. * Texture used in all pbr material as the reflection texture.
  23674. * As in the majority of the scene they are the same (exception for multi room and so on),
  23675. * this is easier to set here than in all the materials.
  23676. */
  23677. set: function (value) {
  23678. if (this._environmentTexture === value) {
  23679. return;
  23680. }
  23681. this._environmentTexture = value;
  23682. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23683. },
  23684. enumerable: true,
  23685. configurable: true
  23686. });
  23687. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23688. /**
  23689. * Default image processing configuration used either in the rendering
  23690. * Forward main pass or through the imageProcessingPostProcess if present.
  23691. * As in the majority of the scene they are the same (exception for multi camera),
  23692. * this is easier to reference from here than from all the materials and post process.
  23693. *
  23694. * No setter as we it is a shared configuration, you can set the values instead.
  23695. */
  23696. get: function () {
  23697. return this._imageProcessingConfiguration;
  23698. },
  23699. enumerable: true,
  23700. configurable: true
  23701. });
  23702. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23703. get: function () {
  23704. return this._forceWireframe;
  23705. },
  23706. /**
  23707. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23708. */
  23709. set: function (value) {
  23710. if (this._forceWireframe === value) {
  23711. return;
  23712. }
  23713. this._forceWireframe = value;
  23714. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23720. get: function () {
  23721. return this._forcePointsCloud;
  23722. },
  23723. /**
  23724. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23725. */
  23726. set: function (value) {
  23727. if (this._forcePointsCloud === value) {
  23728. return;
  23729. }
  23730. this._forcePointsCloud = value;
  23731. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23732. },
  23733. enumerable: true,
  23734. configurable: true
  23735. });
  23736. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23737. /**
  23738. * Gets or sets the animation properties override
  23739. */
  23740. get: function () {
  23741. return this._animationPropertiesOverride;
  23742. },
  23743. set: function (value) {
  23744. this._animationPropertiesOverride = value;
  23745. },
  23746. enumerable: true,
  23747. configurable: true
  23748. });
  23749. Object.defineProperty(Scene.prototype, "onDispose", {
  23750. /** Sets a function to be executed when this scene is disposed. */
  23751. set: function (callback) {
  23752. if (this._onDisposeObserver) {
  23753. this.onDisposeObservable.remove(this._onDisposeObserver);
  23754. }
  23755. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23756. },
  23757. enumerable: true,
  23758. configurable: true
  23759. });
  23760. Object.defineProperty(Scene.prototype, "beforeRender", {
  23761. /** Sets a function to be executed before rendering this scene */
  23762. set: function (callback) {
  23763. if (this._onBeforeRenderObserver) {
  23764. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23765. }
  23766. if (callback) {
  23767. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23768. }
  23769. },
  23770. enumerable: true,
  23771. configurable: true
  23772. });
  23773. Object.defineProperty(Scene.prototype, "afterRender", {
  23774. /** Sets a function to be executed after rendering this scene */
  23775. set: function (callback) {
  23776. if (this._onAfterRenderObserver) {
  23777. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23778. }
  23779. if (callback) {
  23780. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23781. }
  23782. },
  23783. enumerable: true,
  23784. configurable: true
  23785. });
  23786. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23787. /** Sets a function to be executed before rendering a camera*/
  23788. set: function (callback) {
  23789. if (this._onBeforeCameraRenderObserver) {
  23790. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23791. }
  23792. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23793. },
  23794. enumerable: true,
  23795. configurable: true
  23796. });
  23797. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23798. /** Sets a function to be executed after rendering a camera*/
  23799. set: function (callback) {
  23800. if (this._onAfterCameraRenderObserver) {
  23801. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23802. }
  23803. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23804. },
  23805. enumerable: true,
  23806. configurable: true
  23807. });
  23808. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23809. /**
  23810. * Gets the gamepad manager associated with the scene
  23811. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23812. */
  23813. get: function () {
  23814. if (!this._gamepadManager) {
  23815. this._gamepadManager = new BABYLON.GamepadManager(this);
  23816. }
  23817. return this._gamepadManager;
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23823. /**
  23824. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23825. */
  23826. get: function () {
  23827. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23828. },
  23829. enumerable: true,
  23830. configurable: true
  23831. });
  23832. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23833. get: function () {
  23834. return this._useRightHandedSystem;
  23835. },
  23836. /**
  23837. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23838. */
  23839. set: function (value) {
  23840. if (this._useRightHandedSystem === value) {
  23841. return;
  23842. }
  23843. this._useRightHandedSystem = value;
  23844. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23845. },
  23846. enumerable: true,
  23847. configurable: true
  23848. });
  23849. /**
  23850. * Sets the step Id used by deterministic lock step
  23851. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23852. * @param newStepId defines the step Id
  23853. */
  23854. Scene.prototype.setStepId = function (newStepId) {
  23855. this._currentStepId = newStepId;
  23856. };
  23857. ;
  23858. /**
  23859. * Gets the step Id used by deterministic lock step
  23860. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23861. * @returns the step Id
  23862. */
  23863. Scene.prototype.getStepId = function () {
  23864. return this._currentStepId;
  23865. };
  23866. ;
  23867. /**
  23868. * Gets the internal step used by deterministic lock step
  23869. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23870. * @returns the internal step
  23871. */
  23872. Scene.prototype.getInternalStep = function () {
  23873. return this._currentInternalStep;
  23874. };
  23875. ;
  23876. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23877. get: function () {
  23878. return this._fogEnabled;
  23879. },
  23880. /**
  23881. * Gets or sets a boolean indicating if fog is enabled on this scene
  23882. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23883. */
  23884. set: function (value) {
  23885. if (this._fogEnabled === value) {
  23886. return;
  23887. }
  23888. this._fogEnabled = value;
  23889. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23890. },
  23891. enumerable: true,
  23892. configurable: true
  23893. });
  23894. Object.defineProperty(Scene.prototype, "fogMode", {
  23895. get: function () {
  23896. return this._fogMode;
  23897. },
  23898. /**
  23899. * Gets or sets the fog mode to use
  23900. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23901. */
  23902. set: function (value) {
  23903. if (this._fogMode === value) {
  23904. return;
  23905. }
  23906. this._fogMode = value;
  23907. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23913. get: function () {
  23914. return this._shadowsEnabled;
  23915. },
  23916. /**
  23917. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23918. */
  23919. set: function (value) {
  23920. if (this._shadowsEnabled === value) {
  23921. return;
  23922. }
  23923. this._shadowsEnabled = value;
  23924. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23925. },
  23926. enumerable: true,
  23927. configurable: true
  23928. });
  23929. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23930. get: function () {
  23931. return this._lightsEnabled;
  23932. },
  23933. /**
  23934. * Gets or sets a boolean indicating if lights are enabled on this scene
  23935. */
  23936. set: function (value) {
  23937. if (this._lightsEnabled === value) {
  23938. return;
  23939. }
  23940. this._lightsEnabled = value;
  23941. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23947. /** The default material used on meshes when no material is affected */
  23948. get: function () {
  23949. if (!this._defaultMaterial) {
  23950. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23951. }
  23952. return this._defaultMaterial;
  23953. },
  23954. /** The default material used on meshes when no material is affected */
  23955. set: function (value) {
  23956. this._defaultMaterial = value;
  23957. },
  23958. enumerable: true,
  23959. configurable: true
  23960. });
  23961. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23962. get: function () {
  23963. return this._texturesEnabled;
  23964. },
  23965. /**
  23966. * Gets or sets a boolean indicating if textures are enabled on this scene
  23967. */
  23968. set: function (value) {
  23969. if (this._texturesEnabled === value) {
  23970. return;
  23971. }
  23972. this._texturesEnabled = value;
  23973. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23979. get: function () {
  23980. return this._skeletonsEnabled;
  23981. },
  23982. /**
  23983. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23984. */
  23985. set: function (value) {
  23986. if (this._skeletonsEnabled === value) {
  23987. return;
  23988. }
  23989. this._skeletonsEnabled = value;
  23990. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23991. },
  23992. enumerable: true,
  23993. configurable: true
  23994. });
  23995. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23996. /**
  23997. * Gets the postprocess render pipeline manager
  23998. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23999. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24000. */
  24001. get: function () {
  24002. if (!this._postProcessRenderPipelineManager) {
  24003. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24004. }
  24005. return this._postProcessRenderPipelineManager;
  24006. },
  24007. enumerable: true,
  24008. configurable: true
  24009. });
  24010. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24011. /**
  24012. * Gets the main soundtrack associated with the scene
  24013. */
  24014. get: function () {
  24015. if (!this._mainSoundTrack) {
  24016. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24017. }
  24018. return this._mainSoundTrack;
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24024. /** @ignore */
  24025. get: function () {
  24026. return this._alternateRendering;
  24027. },
  24028. enumerable: true,
  24029. configurable: true
  24030. });
  24031. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24032. /**
  24033. * Gets the list of frustum planes (built from the active camera)
  24034. */
  24035. get: function () {
  24036. return this._frustumPlanes;
  24037. },
  24038. enumerable: true,
  24039. configurable: true
  24040. });
  24041. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24042. /**
  24043. * Gets the current geometry buffer associated to the scene.
  24044. */
  24045. get: function () {
  24046. return this._geometryBufferRenderer;
  24047. },
  24048. /**
  24049. * Sets the current geometry buffer for the scene.
  24050. */
  24051. set: function (geometryBufferRenderer) {
  24052. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24053. this._geometryBufferRenderer = geometryBufferRenderer;
  24054. }
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(Scene.prototype, "debugLayer", {
  24060. /**
  24061. * Gets the debug layer associated with the scene
  24062. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24063. */
  24064. get: function () {
  24065. if (!this._debugLayer) {
  24066. this._debugLayer = new BABYLON.DebugLayer(this);
  24067. }
  24068. return this._debugLayer;
  24069. },
  24070. enumerable: true,
  24071. configurable: true
  24072. });
  24073. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24074. /**
  24075. * Gets a boolean indicating if collisions are processed on a web worker
  24076. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24077. */
  24078. get: function () {
  24079. return this._workerCollisions;
  24080. },
  24081. set: function (enabled) {
  24082. if (!BABYLON.CollisionCoordinatorLegacy) {
  24083. return;
  24084. }
  24085. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24086. this._workerCollisions = enabled;
  24087. if (this.collisionCoordinator) {
  24088. this.collisionCoordinator.destroy();
  24089. }
  24090. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24091. this.collisionCoordinator.init(this);
  24092. },
  24093. enumerable: true,
  24094. configurable: true
  24095. });
  24096. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24097. /**
  24098. * Gets the octree used to boost mesh selection (picking)
  24099. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24100. */
  24101. get: function () {
  24102. return this._selectionOctree;
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24108. /**
  24109. * Gets the mesh that is currently under the pointer
  24110. */
  24111. get: function () {
  24112. return this._pointerOverMesh;
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. Object.defineProperty(Scene.prototype, "pointerX", {
  24118. /**
  24119. * Gets the current on-screen X position of the pointer
  24120. */
  24121. get: function () {
  24122. return this._pointerX;
  24123. },
  24124. enumerable: true,
  24125. configurable: true
  24126. });
  24127. Object.defineProperty(Scene.prototype, "pointerY", {
  24128. /**
  24129. * Gets the current on-screen Y position of the pointer
  24130. */
  24131. get: function () {
  24132. return this._pointerY;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. /**
  24138. * Gets the cached material (ie. the latest rendered one)
  24139. * @returns the cached material
  24140. */
  24141. Scene.prototype.getCachedMaterial = function () {
  24142. return this._cachedMaterial;
  24143. };
  24144. /**
  24145. * Gets the cached effect (ie. the latest rendered one)
  24146. * @returns the cached effect
  24147. */
  24148. Scene.prototype.getCachedEffect = function () {
  24149. return this._cachedEffect;
  24150. };
  24151. /**
  24152. * Gets the cached visibility state (ie. the latest rendered one)
  24153. * @returns the cached visibility state
  24154. */
  24155. Scene.prototype.getCachedVisibility = function () {
  24156. return this._cachedVisibility;
  24157. };
  24158. /**
  24159. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24160. * @param material defines the current material
  24161. * @param effect defines the current effect
  24162. * @param visibility defines the current visibility state
  24163. * @returns true if one parameter is not cached
  24164. */
  24165. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24166. if (visibility === void 0) { visibility = 1; }
  24167. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24168. };
  24169. /**
  24170. * Gets the bounding box renderer associated with the scene
  24171. * @returns a BoundingBoxRenderer
  24172. */
  24173. Scene.prototype.getBoundingBoxRenderer = function () {
  24174. if (!this._boundingBoxRenderer) {
  24175. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24176. }
  24177. return this._boundingBoxRenderer;
  24178. };
  24179. /**
  24180. * Gets the outline renderer associated with the scene
  24181. * @returns a OutlineRenderer
  24182. */
  24183. Scene.prototype.getOutlineRenderer = function () {
  24184. return this._outlineRenderer;
  24185. };
  24186. /**
  24187. * Gets the engine associated with the scene
  24188. * @returns an Engine
  24189. */
  24190. Scene.prototype.getEngine = function () {
  24191. return this._engine;
  24192. };
  24193. /**
  24194. * Gets the total number of vertices rendered per frame
  24195. * @returns the total number of vertices rendered per frame
  24196. */
  24197. Scene.prototype.getTotalVertices = function () {
  24198. return this._totalVertices.current;
  24199. };
  24200. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24201. /**
  24202. * Gets the performance counter for total vertices
  24203. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24204. */
  24205. get: function () {
  24206. return this._totalVertices;
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. /**
  24212. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24213. * @returns the total number of active indices rendered per frame
  24214. */
  24215. Scene.prototype.getActiveIndices = function () {
  24216. return this._activeIndices.current;
  24217. };
  24218. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24219. /**
  24220. * Gets the performance counter for active indices
  24221. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24222. */
  24223. get: function () {
  24224. return this._activeIndices;
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. /**
  24230. * Gets the total number of active particles rendered per frame
  24231. * @returns the total number of active particles rendered per frame
  24232. */
  24233. Scene.prototype.getActiveParticles = function () {
  24234. return this._activeParticles.current;
  24235. };
  24236. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24237. /**
  24238. * Gets the performance counter for active particles
  24239. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24240. */
  24241. get: function () {
  24242. return this._activeParticles;
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. /**
  24248. * Gets the total number of active bones rendered per frame
  24249. * @returns the total number of active bones rendered per frame
  24250. */
  24251. Scene.prototype.getActiveBones = function () {
  24252. return this._activeBones.current;
  24253. };
  24254. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24255. /**
  24256. * Gets the performance counter for active bones
  24257. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24258. */
  24259. get: function () {
  24260. return this._activeBones;
  24261. },
  24262. enumerable: true,
  24263. configurable: true
  24264. });
  24265. /** @ignore */
  24266. Scene.prototype.getInterFramePerfCounter = function () {
  24267. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24268. return 0;
  24269. };
  24270. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24271. /** @ignore */
  24272. get: function () {
  24273. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24274. return null;
  24275. },
  24276. enumerable: true,
  24277. configurable: true
  24278. });
  24279. /** @ignore */
  24280. Scene.prototype.getLastFrameDuration = function () {
  24281. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24282. return 0;
  24283. };
  24284. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24285. /** @ignore */
  24286. get: function () {
  24287. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24288. return null;
  24289. },
  24290. enumerable: true,
  24291. configurable: true
  24292. });
  24293. /** @ignore */
  24294. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24295. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24296. return 0;
  24297. };
  24298. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24299. /** @ignore */
  24300. get: function () {
  24301. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24302. return null;
  24303. },
  24304. enumerable: true,
  24305. configurable: true
  24306. });
  24307. /**
  24308. * Gets the array of active meshes
  24309. * @returns an array of AbstractMesh
  24310. */
  24311. Scene.prototype.getActiveMeshes = function () {
  24312. return this._activeMeshes;
  24313. };
  24314. /** @ignore */
  24315. Scene.prototype.getRenderTargetsDuration = function () {
  24316. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24317. return 0;
  24318. };
  24319. /** @ignore */
  24320. Scene.prototype.getRenderDuration = function () {
  24321. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24322. return 0;
  24323. };
  24324. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24325. /** @ignore */
  24326. get: function () {
  24327. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24328. return null;
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. /** @ignore */
  24334. Scene.prototype.getParticlesDuration = function () {
  24335. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24336. return 0;
  24337. };
  24338. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24339. /** @ignore */
  24340. get: function () {
  24341. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24342. return null;
  24343. },
  24344. enumerable: true,
  24345. configurable: true
  24346. });
  24347. /** @ignore */
  24348. Scene.prototype.getSpritesDuration = function () {
  24349. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24350. return 0;
  24351. };
  24352. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24353. /** @ignore */
  24354. get: function () {
  24355. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24356. return null;
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. /**
  24362. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24363. * @returns a number
  24364. */
  24365. Scene.prototype.getAnimationRatio = function () {
  24366. return this._animationRatio;
  24367. };
  24368. /**
  24369. * Gets an unique Id for the current frame
  24370. * @returns a number
  24371. */
  24372. Scene.prototype.getRenderId = function () {
  24373. return this._renderId;
  24374. };
  24375. /** Call this function if you want to manually increment the render Id*/
  24376. Scene.prototype.incrementRenderId = function () {
  24377. this._renderId++;
  24378. };
  24379. Scene.prototype._updatePointerPosition = function (evt) {
  24380. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24381. if (!canvasRect) {
  24382. return;
  24383. }
  24384. this._pointerX = evt.clientX - canvasRect.left;
  24385. this._pointerY = evt.clientY - canvasRect.top;
  24386. this._unTranslatedPointerX = this._pointerX;
  24387. this._unTranslatedPointerY = this._pointerY;
  24388. };
  24389. Scene.prototype._createUbo = function () {
  24390. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24391. this._sceneUbo.addUniform("viewProjection", 16);
  24392. this._sceneUbo.addUniform("view", 16);
  24393. };
  24394. Scene.prototype._createAlternateUbo = function () {
  24395. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24396. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24397. this._alternateSceneUbo.addUniform("view", 16);
  24398. };
  24399. // Pointers handling
  24400. /**
  24401. * Use this method to simulate a pointer move on a mesh
  24402. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24403. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24404. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24405. * @returns the current scene
  24406. */
  24407. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24408. var evt = new PointerEvent("pointermove", pointerEventInit);
  24409. return this._processPointerMove(pickResult, evt);
  24410. };
  24411. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24412. var canvas = this._engine.getRenderingCanvas();
  24413. if (!canvas) {
  24414. return this;
  24415. }
  24416. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24417. this.setPointerOverSprite(null);
  24418. this.setPointerOverMesh(pickResult.pickedMesh);
  24419. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24420. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24421. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24422. }
  24423. else {
  24424. canvas.style.cursor = this.hoverCursor;
  24425. }
  24426. }
  24427. else {
  24428. canvas.style.cursor = this.defaultCursor;
  24429. }
  24430. }
  24431. else {
  24432. this.setPointerOverMesh(null);
  24433. // Sprites
  24434. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24435. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24436. this.setPointerOverSprite(pickResult.pickedSprite);
  24437. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24438. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24439. }
  24440. else {
  24441. canvas.style.cursor = this.hoverCursor;
  24442. }
  24443. }
  24444. else {
  24445. this.setPointerOverSprite(null);
  24446. // Restore pointer
  24447. canvas.style.cursor = this.defaultCursor;
  24448. }
  24449. }
  24450. if (pickResult) {
  24451. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24452. if (this.onPointerMove) {
  24453. this.onPointerMove(evt, pickResult, type);
  24454. }
  24455. if (this.onPointerObservable.hasObservers()) {
  24456. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24457. this.onPointerObservable.notifyObservers(pi, type);
  24458. }
  24459. }
  24460. return this;
  24461. };
  24462. /**
  24463. * Use this method to simulate a pointer down on a mesh
  24464. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24465. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24466. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24467. * @returns the current scene
  24468. */
  24469. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24470. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24471. return this._processPointerDown(pickResult, evt);
  24472. };
  24473. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24474. var _this = this;
  24475. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24476. this._pickedDownMesh = pickResult.pickedMesh;
  24477. var actionManager = pickResult.pickedMesh.actionManager;
  24478. if (actionManager) {
  24479. if (actionManager.hasPickTriggers) {
  24480. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24481. switch (evt.button) {
  24482. case 0:
  24483. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24484. break;
  24485. case 1:
  24486. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24487. break;
  24488. case 2:
  24489. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24490. break;
  24491. }
  24492. }
  24493. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24494. window.setTimeout(function () {
  24495. 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);
  24496. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24497. if (_this._totalPointersPressed !== 0 &&
  24498. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24499. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24500. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24501. _this._startingPointerTime = 0;
  24502. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24503. }
  24504. }
  24505. }, Scene.LongPressDelay);
  24506. }
  24507. }
  24508. }
  24509. if (pickResult) {
  24510. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24511. if (this.onPointerDown) {
  24512. this.onPointerDown(evt, pickResult, type);
  24513. }
  24514. if (this.onPointerObservable.hasObservers()) {
  24515. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24516. this.onPointerObservable.notifyObservers(pi, type);
  24517. }
  24518. }
  24519. return this;
  24520. };
  24521. /**
  24522. * Use this method to simulate a pointer up on a mesh
  24523. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24524. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24525. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24526. * @returns the current scene
  24527. */
  24528. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24529. var evt = new PointerEvent("pointerup", pointerEventInit);
  24530. var clickInfo = new ClickInfo();
  24531. clickInfo.singleClick = true;
  24532. clickInfo.ignore = true;
  24533. return this._processPointerUp(pickResult, evt, clickInfo);
  24534. };
  24535. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24536. if (pickResult && pickResult && pickResult.pickedMesh) {
  24537. this._pickedUpMesh = pickResult.pickedMesh;
  24538. if (this._pickedDownMesh === this._pickedUpMesh) {
  24539. if (this.onPointerPick) {
  24540. this.onPointerPick(evt, pickResult);
  24541. }
  24542. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24543. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24544. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24545. this.onPointerObservable.notifyObservers(pi, type_1);
  24546. }
  24547. }
  24548. if (pickResult.pickedMesh.actionManager) {
  24549. if (clickInfo.ignore) {
  24550. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24551. }
  24552. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24553. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24554. }
  24555. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24556. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24557. }
  24558. }
  24559. }
  24560. if (this._pickedDownMesh &&
  24561. this._pickedDownMesh.actionManager &&
  24562. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24563. this._pickedDownMesh !== this._pickedUpMesh) {
  24564. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24565. }
  24566. var type = BABYLON.PointerEventTypes.POINTERUP;
  24567. if (this.onPointerObservable.hasObservers()) {
  24568. if (!clickInfo.ignore) {
  24569. if (!clickInfo.hasSwiped) {
  24570. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24571. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24572. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24573. this.onPointerObservable.notifyObservers(pi, type_2);
  24574. }
  24575. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24576. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24577. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24578. this.onPointerObservable.notifyObservers(pi, type_3);
  24579. }
  24580. }
  24581. }
  24582. else {
  24583. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24584. this.onPointerObservable.notifyObservers(pi, type);
  24585. }
  24586. }
  24587. if (this.onPointerUp) {
  24588. this.onPointerUp(evt, pickResult, type);
  24589. }
  24590. return this;
  24591. };
  24592. /**
  24593. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24594. * @param attachUp defines if you want to attach events to pointerup
  24595. * @param attachDown defines if you want to attach events to pointerdown
  24596. * @param attachMove defines if you want to attach events to pointermove
  24597. */
  24598. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24599. var _this = this;
  24600. if (attachUp === void 0) { attachUp = true; }
  24601. if (attachDown === void 0) { attachDown = true; }
  24602. if (attachMove === void 0) { attachMove = true; }
  24603. this._initActionManager = function (act, clickInfo) {
  24604. if (!_this._meshPickProceed) {
  24605. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24606. _this._currentPickResult = pickResult;
  24607. if (pickResult) {
  24608. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24609. }
  24610. _this._meshPickProceed = true;
  24611. }
  24612. return act;
  24613. };
  24614. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24615. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24616. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24617. btn !== _this._previousButtonPressed) {
  24618. _this._doubleClickOccured = false;
  24619. clickInfo.singleClick = true;
  24620. clickInfo.ignore = false;
  24621. cb(clickInfo, _this._currentPickResult);
  24622. }
  24623. };
  24624. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24625. var clickInfo = new ClickInfo();
  24626. _this._currentPickResult = null;
  24627. var act = null;
  24628. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24629. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24630. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24631. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24632. act = _this._initActionManager(act, clickInfo);
  24633. if (act)
  24634. checkPicking = act.hasPickTriggers;
  24635. }
  24636. if (checkPicking) {
  24637. var btn = evt.button;
  24638. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24639. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24640. if (!clickInfo.hasSwiped) {
  24641. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24642. if (!checkSingleClickImmediately) {
  24643. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24644. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24645. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24646. act = _this._initActionManager(act, clickInfo);
  24647. if (act)
  24648. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24649. }
  24650. }
  24651. if (checkSingleClickImmediately) {
  24652. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24653. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24654. btn !== _this._previousButtonPressed) {
  24655. clickInfo.singleClick = true;
  24656. cb(clickInfo, _this._currentPickResult);
  24657. }
  24658. }
  24659. // at least one double click is required to be check and exclusive double click is enabled
  24660. else {
  24661. // wait that no double click has been raised during the double click delay
  24662. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24663. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24664. }
  24665. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24666. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24667. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24668. act = _this._initActionManager(act, clickInfo);
  24669. if (act)
  24670. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24671. }
  24672. if (checkDoubleClick) {
  24673. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24674. if (btn === _this._previousButtonPressed &&
  24675. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24676. !_this._doubleClickOccured) {
  24677. // pointer has not moved for 2 clicks, it's a double click
  24678. if (!clickInfo.hasSwiped &&
  24679. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24680. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24681. _this._previousStartingPointerTime = 0;
  24682. _this._doubleClickOccured = true;
  24683. clickInfo.doubleClick = true;
  24684. clickInfo.ignore = false;
  24685. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24686. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24687. }
  24688. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24689. cb(clickInfo, _this._currentPickResult);
  24690. }
  24691. // if the two successive clicks are too far, it's just two simple clicks
  24692. else {
  24693. _this._doubleClickOccured = false;
  24694. _this._previousStartingPointerTime = _this._startingPointerTime;
  24695. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24696. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24697. _this._previousButtonPressed = btn;
  24698. if (Scene.ExclusiveDoubleClickMode) {
  24699. if (_this._previousDelayedSimpleClickTimeout) {
  24700. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24701. }
  24702. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24703. cb(clickInfo, _this._previousPickResult);
  24704. }
  24705. else {
  24706. cb(clickInfo, _this._currentPickResult);
  24707. }
  24708. }
  24709. }
  24710. // just the first click of the double has been raised
  24711. else {
  24712. _this._doubleClickOccured = false;
  24713. _this._previousStartingPointerTime = _this._startingPointerTime;
  24714. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24715. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24716. _this._previousButtonPressed = btn;
  24717. }
  24718. }
  24719. }
  24720. }
  24721. clickInfo.ignore = true;
  24722. cb(clickInfo, _this._currentPickResult);
  24723. };
  24724. this._spritePredicate = function (sprite) {
  24725. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24726. };
  24727. this._onPointerMove = function (evt) {
  24728. _this._updatePointerPosition(evt);
  24729. // PreObservable support
  24730. if (_this.onPrePointerObservable.hasObservers()) {
  24731. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24732. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24733. _this.onPrePointerObservable.notifyObservers(pi, type);
  24734. if (pi.skipOnPointerObservable) {
  24735. return;
  24736. }
  24737. }
  24738. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24739. return;
  24740. }
  24741. if (!_this.pointerMovePredicate) {
  24742. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24743. }
  24744. // Meshes
  24745. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24746. _this._processPointerMove(pickResult, evt);
  24747. };
  24748. this._onPointerDown = function (evt) {
  24749. _this._totalPointersPressed++;
  24750. _this._pickedDownMesh = null;
  24751. _this._meshPickProceed = false;
  24752. _this._updatePointerPosition(evt);
  24753. if (_this.preventDefaultOnPointerDown && canvas) {
  24754. evt.preventDefault();
  24755. canvas.focus();
  24756. }
  24757. // PreObservable support
  24758. if (_this.onPrePointerObservable.hasObservers()) {
  24759. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24760. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24761. _this.onPrePointerObservable.notifyObservers(pi, type);
  24762. if (pi.skipOnPointerObservable) {
  24763. return;
  24764. }
  24765. }
  24766. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24767. return;
  24768. }
  24769. _this._startingPointerPosition.x = _this._pointerX;
  24770. _this._startingPointerPosition.y = _this._pointerY;
  24771. _this._startingPointerTime = Date.now();
  24772. if (!_this.pointerDownPredicate) {
  24773. _this.pointerDownPredicate = function (mesh) {
  24774. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24775. };
  24776. }
  24777. // Meshes
  24778. _this._pickedDownMesh = null;
  24779. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24780. _this._processPointerDown(pickResult, evt);
  24781. // Sprites
  24782. _this._pickedDownSprite = null;
  24783. if (_this.spriteManagers.length > 0) {
  24784. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24785. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24786. if (pickResult.pickedSprite.actionManager) {
  24787. _this._pickedDownSprite = pickResult.pickedSprite;
  24788. switch (evt.button) {
  24789. case 0:
  24790. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24791. break;
  24792. case 1:
  24793. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24794. break;
  24795. case 2:
  24796. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24797. break;
  24798. }
  24799. if (pickResult.pickedSprite.actionManager) {
  24800. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24801. }
  24802. }
  24803. }
  24804. }
  24805. };
  24806. this._onPointerUp = function (evt) {
  24807. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  24808. return; // So we need to test it the pointer down was pressed before.
  24809. }
  24810. _this._totalPointersPressed--;
  24811. _this._pickedUpMesh = null;
  24812. _this._meshPickProceed = false;
  24813. _this._updatePointerPosition(evt);
  24814. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24815. // PreObservable support
  24816. if (_this.onPrePointerObservable.hasObservers()) {
  24817. if (!clickInfo.ignore) {
  24818. if (!clickInfo.hasSwiped) {
  24819. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24820. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24821. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24822. _this.onPrePointerObservable.notifyObservers(pi, type);
  24823. if (pi.skipOnPointerObservable) {
  24824. return;
  24825. }
  24826. }
  24827. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24828. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24829. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24830. _this.onPrePointerObservable.notifyObservers(pi, type);
  24831. if (pi.skipOnPointerObservable) {
  24832. return;
  24833. }
  24834. }
  24835. }
  24836. }
  24837. else {
  24838. var type = BABYLON.PointerEventTypes.POINTERUP;
  24839. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24840. _this.onPrePointerObservable.notifyObservers(pi, type);
  24841. if (pi.skipOnPointerObservable) {
  24842. return;
  24843. }
  24844. }
  24845. }
  24846. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24847. return;
  24848. }
  24849. if (!_this.pointerUpPredicate) {
  24850. _this.pointerUpPredicate = function (mesh) {
  24851. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24852. };
  24853. }
  24854. // Meshes
  24855. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24856. _this._initActionManager(null, clickInfo);
  24857. }
  24858. if (!pickResult) {
  24859. pickResult = _this._currentPickResult;
  24860. }
  24861. _this._processPointerUp(pickResult, evt, clickInfo);
  24862. // Sprites
  24863. if (_this.spriteManagers.length > 0) {
  24864. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24865. if (spritePickResult) {
  24866. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24867. if (spritePickResult.pickedSprite.actionManager) {
  24868. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24869. if (spritePickResult.pickedSprite.actionManager) {
  24870. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24871. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24872. }
  24873. }
  24874. }
  24875. }
  24876. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24877. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24878. }
  24879. }
  24880. }
  24881. _this._previousPickResult = _this._currentPickResult;
  24882. });
  24883. };
  24884. this._onKeyDown = function (evt) {
  24885. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24886. if (_this.onPreKeyboardObservable.hasObservers()) {
  24887. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24888. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24889. if (pi.skipOnPointerObservable) {
  24890. return;
  24891. }
  24892. }
  24893. if (_this.onKeyboardObservable.hasObservers()) {
  24894. var pi = new BABYLON.KeyboardInfo(type, evt);
  24895. _this.onKeyboardObservable.notifyObservers(pi, type);
  24896. }
  24897. if (_this.actionManager) {
  24898. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24899. }
  24900. };
  24901. this._onKeyUp = function (evt) {
  24902. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24903. if (_this.onPreKeyboardObservable.hasObservers()) {
  24904. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24905. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24906. if (pi.skipOnPointerObservable) {
  24907. return;
  24908. }
  24909. }
  24910. if (_this.onKeyboardObservable.hasObservers()) {
  24911. var pi = new BABYLON.KeyboardInfo(type, evt);
  24912. _this.onKeyboardObservable.notifyObservers(pi, type);
  24913. }
  24914. if (_this.actionManager) {
  24915. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24916. }
  24917. };
  24918. var engine = this.getEngine();
  24919. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24920. if (!canvas) {
  24921. return;
  24922. }
  24923. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24924. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24925. });
  24926. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24927. if (!canvas) {
  24928. return;
  24929. }
  24930. canvas.removeEventListener("keydown", _this._onKeyDown);
  24931. canvas.removeEventListener("keyup", _this._onKeyUp);
  24932. });
  24933. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24934. var canvas = this._engine.getRenderingCanvas();
  24935. if (!canvas) {
  24936. return;
  24937. }
  24938. if (attachMove) {
  24939. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24940. // Wheel
  24941. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24942. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24943. }
  24944. if (attachDown) {
  24945. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24946. }
  24947. if (attachUp) {
  24948. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24949. }
  24950. canvas.tabIndex = 1;
  24951. };
  24952. /** Detaches all event handlers*/
  24953. Scene.prototype.detachControl = function () {
  24954. var engine = this.getEngine();
  24955. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24956. var canvas = engine.getRenderingCanvas();
  24957. if (!canvas) {
  24958. return;
  24959. }
  24960. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24961. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24962. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24963. if (this._onCanvasBlurObserver) {
  24964. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24965. }
  24966. if (this._onCanvasFocusObserver) {
  24967. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24968. }
  24969. // Wheel
  24970. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24971. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24972. // Keyboard
  24973. canvas.removeEventListener("keydown", this._onKeyDown);
  24974. canvas.removeEventListener("keyup", this._onKeyUp);
  24975. // Observables
  24976. this.onKeyboardObservable.clear();
  24977. this.onPreKeyboardObservable.clear();
  24978. this.onPointerObservable.clear();
  24979. this.onPrePointerObservable.clear();
  24980. };
  24981. /**
  24982. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24983. * Delay loaded resources are not taking in account
  24984. * @return true if all required resources are ready
  24985. */
  24986. Scene.prototype.isReady = function () {
  24987. if (this._isDisposed) {
  24988. return false;
  24989. }
  24990. if (this._pendingData.length > 0) {
  24991. return false;
  24992. }
  24993. var index;
  24994. var engine = this.getEngine();
  24995. // Geometries
  24996. for (index = 0; index < this._geometries.length; index++) {
  24997. var geometry = this._geometries[index];
  24998. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24999. return false;
  25000. }
  25001. }
  25002. // Meshes
  25003. for (index = 0; index < this.meshes.length; index++) {
  25004. var mesh = this.meshes[index];
  25005. if (!mesh.isEnabled()) {
  25006. continue;
  25007. }
  25008. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25009. continue;
  25010. }
  25011. if (!mesh.isReady(true)) {
  25012. return false;
  25013. }
  25014. // Effect layers
  25015. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25016. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25017. var layer = _a[_i];
  25018. if (!layer.hasMesh(mesh)) {
  25019. continue;
  25020. }
  25021. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25022. var subMesh = _c[_b];
  25023. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25024. return false;
  25025. }
  25026. }
  25027. }
  25028. }
  25029. // Post-processes
  25030. if (this.activeCameras && this.activeCameras.length > 0) {
  25031. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25032. var camera = _e[_d];
  25033. if (!camera.isReady(true)) {
  25034. return false;
  25035. }
  25036. }
  25037. }
  25038. else if (this.activeCamera) {
  25039. if (!this.activeCamera.isReady(true)) {
  25040. return false;
  25041. }
  25042. }
  25043. // Particles
  25044. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25045. var particleSystem = _g[_f];
  25046. if (!particleSystem.isReady()) {
  25047. return false;
  25048. }
  25049. }
  25050. return true;
  25051. };
  25052. /** Resets all cached information relative to material (including effect and visibility) */
  25053. Scene.prototype.resetCachedMaterial = function () {
  25054. this._cachedMaterial = null;
  25055. this._cachedEffect = null;
  25056. this._cachedVisibility = null;
  25057. };
  25058. /**
  25059. * Registers a function to be called before every frame render
  25060. * @param func defines the function to register
  25061. */
  25062. Scene.prototype.registerBeforeRender = function (func) {
  25063. this.onBeforeRenderObservable.add(func);
  25064. };
  25065. /**
  25066. * Unregisters a function called before every frame render
  25067. * @param func defines the function to unregister
  25068. */
  25069. Scene.prototype.unregisterBeforeRender = function (func) {
  25070. this.onBeforeRenderObservable.removeCallback(func);
  25071. };
  25072. /**
  25073. * Registers a function to be called after every frame render
  25074. * @param func defines the function to register
  25075. */
  25076. Scene.prototype.registerAfterRender = function (func) {
  25077. this.onAfterRenderObservable.add(func);
  25078. };
  25079. /**
  25080. * Unregisters a function called after every frame render
  25081. * @param func defines the function to unregister
  25082. */
  25083. Scene.prototype.unregisterAfterRender = function (func) {
  25084. this.onAfterRenderObservable.removeCallback(func);
  25085. };
  25086. Scene.prototype._executeOnceBeforeRender = function (func) {
  25087. var _this = this;
  25088. var execFunc = function () {
  25089. func();
  25090. setTimeout(function () {
  25091. _this.unregisterBeforeRender(execFunc);
  25092. });
  25093. };
  25094. this.registerBeforeRender(execFunc);
  25095. };
  25096. /**
  25097. * The provided function will run before render once and will be disposed afterwards.
  25098. * A timeout delay can be provided so that the function will be executed in N ms.
  25099. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25100. * @param func The function to be executed.
  25101. * @param timeout optional delay in ms
  25102. */
  25103. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25104. var _this = this;
  25105. if (timeout !== undefined) {
  25106. setTimeout(function () {
  25107. _this._executeOnceBeforeRender(func);
  25108. }, timeout);
  25109. }
  25110. else {
  25111. this._executeOnceBeforeRender(func);
  25112. }
  25113. };
  25114. /** @ignore */
  25115. Scene.prototype._addPendingData = function (data) {
  25116. this._pendingData.push(data);
  25117. };
  25118. /** @ignore */
  25119. Scene.prototype._removePendingData = function (data) {
  25120. var wasLoading = this.isLoading;
  25121. var index = this._pendingData.indexOf(data);
  25122. if (index !== -1) {
  25123. this._pendingData.splice(index, 1);
  25124. }
  25125. if (wasLoading && !this.isLoading) {
  25126. this.onDataLoadedObservable.notifyObservers(this);
  25127. }
  25128. };
  25129. /**
  25130. * Returns the number of items waiting to be loaded
  25131. * @returns the number of items waiting to be loaded
  25132. */
  25133. Scene.prototype.getWaitingItemsCount = function () {
  25134. return this._pendingData.length;
  25135. };
  25136. Object.defineProperty(Scene.prototype, "isLoading", {
  25137. /**
  25138. * Returns a boolean indicating if the scene is still loading data
  25139. */
  25140. get: function () {
  25141. return this._pendingData.length > 0;
  25142. },
  25143. enumerable: true,
  25144. configurable: true
  25145. });
  25146. /**
  25147. * Registers a function to be executed when the scene is ready
  25148. * @param {Function} func - the function to be executed
  25149. */
  25150. Scene.prototype.executeWhenReady = function (func) {
  25151. var _this = this;
  25152. this.onReadyObservable.add(func);
  25153. if (this._executeWhenReadyTimeoutId !== -1) {
  25154. return;
  25155. }
  25156. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25157. _this._checkIsReady();
  25158. }, 150);
  25159. };
  25160. /**
  25161. * Returns a promise that resolves when the scene is ready
  25162. * @returns A promise that resolves when the scene is ready
  25163. */
  25164. Scene.prototype.whenReadyAsync = function () {
  25165. var _this = this;
  25166. return new Promise(function (resolve) {
  25167. _this.executeWhenReady(function () {
  25168. resolve();
  25169. });
  25170. });
  25171. };
  25172. /** @ignore */
  25173. Scene.prototype._checkIsReady = function () {
  25174. var _this = this;
  25175. if (this.isReady()) {
  25176. this.onReadyObservable.notifyObservers(this);
  25177. this.onReadyObservable.clear();
  25178. this._executeWhenReadyTimeoutId = -1;
  25179. return;
  25180. }
  25181. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25182. _this._checkIsReady();
  25183. }, 150);
  25184. };
  25185. // Animations
  25186. /**
  25187. * Will start the animation sequence of a given target
  25188. * @param target defines the target
  25189. * @param from defines from which frame should animation start
  25190. * @param to defines until which frame should animation run.
  25191. * @param weight defines the weight to apply to the animation (1.0 by default)
  25192. * @param loop defines if the animation loops
  25193. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25194. * @param onAnimationEnd defines the function to be executed when the animation ends
  25195. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25196. * @returns the animatable object created for this animation
  25197. */
  25198. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25199. if (weight === void 0) { weight = 1.0; }
  25200. if (speedRatio === void 0) { speedRatio = 1.0; }
  25201. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25202. returnedAnimatable.weight = weight;
  25203. return returnedAnimatable;
  25204. };
  25205. /**
  25206. * Will start the animation sequence of a given target
  25207. * @param target defines the target
  25208. * @param from defines from which frame should animation start
  25209. * @param to defines until which frame should animation run.
  25210. * @param loop defines if the animation loops
  25211. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25212. * @param onAnimationEnd defines the function to be executed when the animation ends
  25213. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25214. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25215. * @returns the animatable object created for this animation
  25216. */
  25217. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25218. if (speedRatio === void 0) { speedRatio = 1.0; }
  25219. if (stopCurrent === void 0) { stopCurrent = true; }
  25220. if (from > to && speedRatio > 0) {
  25221. speedRatio *= -1;
  25222. }
  25223. if (stopCurrent) {
  25224. this.stopAnimation(target);
  25225. }
  25226. if (!animatable) {
  25227. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25228. }
  25229. // Local animations
  25230. if (target.animations) {
  25231. animatable.appendAnimations(target, target.animations);
  25232. }
  25233. // Children animations
  25234. if (target.getAnimatables) {
  25235. var animatables = target.getAnimatables();
  25236. for (var index = 0; index < animatables.length; index++) {
  25237. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25238. }
  25239. }
  25240. animatable.reset();
  25241. return animatable;
  25242. };
  25243. /**
  25244. * Begin a new animation on a given node
  25245. * @param target defines the target where the animation will take place
  25246. * @param animations defines the list of animations to start
  25247. * @param from defines the initial value
  25248. * @param to defines the final value
  25249. * @param loop defines if you want animation to loop (off by default)
  25250. * @param speedRatio defines the speed ratio to apply to all animations
  25251. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25252. * @returns the list of created animatables
  25253. */
  25254. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25255. if (speedRatio === undefined) {
  25256. speedRatio = 1.0;
  25257. }
  25258. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25259. return animatable;
  25260. };
  25261. /**
  25262. * Begin a new animation on a given node and its hierarchy
  25263. * @param target defines the root node where the animation will take place
  25264. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25265. * @param animations defines the list of animations to start
  25266. * @param from defines the initial value
  25267. * @param to defines the final value
  25268. * @param loop defines if you want animation to loop (off by default)
  25269. * @param speedRatio defines the speed ratio to apply to all animations
  25270. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25271. * @returns the list of animatables created for all nodes
  25272. */
  25273. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25274. var children = target.getDescendants(directDescendantsOnly);
  25275. var result = [];
  25276. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25277. var child = children_1[_i];
  25278. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25279. }
  25280. return result;
  25281. };
  25282. /**
  25283. * Gets the animatable associated with a specific target
  25284. * @param target defines the target of the animatable
  25285. * @returns the required animatable if found
  25286. */
  25287. Scene.prototype.getAnimatableByTarget = function (target) {
  25288. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25289. if (this._activeAnimatables[index].target === target) {
  25290. return this._activeAnimatables[index];
  25291. }
  25292. }
  25293. return null;
  25294. };
  25295. /**
  25296. * Gets all animatables associated with a given target
  25297. * @param target defines the target to look animatables for
  25298. * @returns an array of Animatables
  25299. */
  25300. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25301. var result = [];
  25302. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25303. if (this._activeAnimatables[index].target === target) {
  25304. result.push(this._activeAnimatables[index]);
  25305. }
  25306. }
  25307. return result;
  25308. };
  25309. Object.defineProperty(Scene.prototype, "animatables", {
  25310. /**
  25311. * Gets all animatable attached to the scene
  25312. */
  25313. get: function () {
  25314. return this._activeAnimatables;
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. /**
  25320. * Will stop the animation of the given target
  25321. * @param target - the target
  25322. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25323. */
  25324. Scene.prototype.stopAnimation = function (target, animationName) {
  25325. var animatables = this.getAllAnimatablesByTarget(target);
  25326. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25327. var animatable = animatables_1[_i];
  25328. animatable.stop(animationName);
  25329. }
  25330. };
  25331. /**
  25332. * Stops and removes all animations that have been applied to the scene
  25333. */
  25334. Scene.prototype.stopAllAnimations = function () {
  25335. if (this._activeAnimatables) {
  25336. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25337. this._activeAnimatables[i].stop();
  25338. }
  25339. this._activeAnimatables = [];
  25340. }
  25341. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25342. var group = _a[_i];
  25343. group.stop();
  25344. }
  25345. };
  25346. Scene.prototype._animate = function () {
  25347. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25348. return;
  25349. }
  25350. // Getting time
  25351. var now = BABYLON.Tools.Now;
  25352. if (!this._animationTimeLast) {
  25353. if (this._pendingData.length > 0) {
  25354. return;
  25355. }
  25356. this._animationTimeLast = now;
  25357. }
  25358. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25359. this._animationTime += deltaTime;
  25360. this._animationTimeLast = now;
  25361. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25362. this._activeAnimatables[index]._animate(this._animationTime);
  25363. }
  25364. // Late animation bindings
  25365. this._processLateAnimationBindings();
  25366. };
  25367. /** @ignore */
  25368. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25369. var target = runtimeAnimation.target;
  25370. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25371. if (!target._lateAnimationHolders) {
  25372. target._lateAnimationHolders = {};
  25373. }
  25374. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25375. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25376. totalWeight: 0,
  25377. animations: []
  25378. };
  25379. }
  25380. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25381. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25382. };
  25383. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25384. var normalizer = 1.0;
  25385. var finalPosition = BABYLON.Tmp.Vector3[0];
  25386. var finalScaling = BABYLON.Tmp.Vector3[1];
  25387. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25388. var startIndex = 0;
  25389. var originalAnimation = holder.animations[0];
  25390. var scale = 1;
  25391. if (holder.totalWeight < 1.0) {
  25392. // We need to mix the original value in
  25393. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25394. scale = 1.0 - holder.totalWeight;
  25395. }
  25396. else {
  25397. startIndex = 1;
  25398. // We need to normalize the weights
  25399. normalizer = holder.totalWeight;
  25400. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25401. scale = originalAnimation.weight / normalizer;
  25402. if (scale == 1) {
  25403. return originalAnimation.currentValue;
  25404. }
  25405. }
  25406. finalScaling.scaleInPlace(scale);
  25407. finalPosition.scaleInPlace(scale);
  25408. finalQuaternion.scaleInPlace(scale);
  25409. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25410. var runtimeAnimation = holder.animations[animIndex];
  25411. var scale = runtimeAnimation.weight / normalizer;
  25412. var currentPosition = BABYLON.Tmp.Vector3[2];
  25413. var currentScaling = BABYLON.Tmp.Vector3[3];
  25414. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25415. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25416. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25417. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25418. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25419. }
  25420. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25421. return originalAnimation._workValue;
  25422. };
  25423. Scene.prototype._processLateAnimationBindings = function () {
  25424. if (!this._registeredForLateAnimationBindings.length) {
  25425. return;
  25426. }
  25427. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25428. var target = this._registeredForLateAnimationBindings.data[index];
  25429. for (var path in target._lateAnimationHolders) {
  25430. var holder = target._lateAnimationHolders[path];
  25431. var originalAnimation = holder.animations[0];
  25432. var originalValue = originalAnimation.originalValue;
  25433. var finalTarget = originalAnimation.target;
  25434. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25435. var finalValue = void 0;
  25436. if (matrixDecomposeMode) {
  25437. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25438. }
  25439. else {
  25440. var startIndex = 0;
  25441. var normalizer = 1.0;
  25442. if (holder.totalWeight < 1.0) {
  25443. // We need to mix the original value in
  25444. if (originalValue.scale) {
  25445. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25446. }
  25447. else {
  25448. finalValue = originalValue * (1.0 - holder.totalWeight);
  25449. }
  25450. }
  25451. else {
  25452. // We need to normalize the weights
  25453. normalizer = holder.totalWeight;
  25454. var scale_1 = originalAnimation.weight / normalizer;
  25455. if (scale_1 !== 1) {
  25456. if (originalAnimation.currentValue.scale) {
  25457. finalValue = originalAnimation.currentValue.scale(scale_1);
  25458. }
  25459. else {
  25460. finalValue = originalAnimation.currentValue * scale_1;
  25461. }
  25462. }
  25463. else {
  25464. finalValue = originalAnimation.currentValue;
  25465. }
  25466. startIndex = 1;
  25467. }
  25468. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25469. var runtimeAnimation = holder.animations[animIndex];
  25470. var scale = runtimeAnimation.weight / normalizer;
  25471. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25472. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25473. }
  25474. else {
  25475. finalValue += runtimeAnimation.currentValue * scale;
  25476. }
  25477. }
  25478. }
  25479. finalTarget[path] = finalValue;
  25480. }
  25481. target._lateAnimationHolders = {};
  25482. }
  25483. this._registeredForLateAnimationBindings.reset();
  25484. };
  25485. // Matrix
  25486. /** @ignore */
  25487. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25488. this._useAlternateCameraConfiguration = active;
  25489. };
  25490. /**
  25491. * Gets the current view matrix
  25492. * @returns a Matrix
  25493. */
  25494. Scene.prototype.getViewMatrix = function () {
  25495. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25496. };
  25497. /**
  25498. * Gets the current projection matrix
  25499. * @returns a Matrix
  25500. */
  25501. Scene.prototype.getProjectionMatrix = function () {
  25502. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25503. };
  25504. /**
  25505. * Gets the current transform matrix
  25506. * @returns a Matrix made of View * Projection
  25507. */
  25508. Scene.prototype.getTransformMatrix = function () {
  25509. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25510. };
  25511. /**
  25512. * Sets the current transform matrix
  25513. * @param view defines the View matrix to use
  25514. * @param projection defines the Projection matrix to use
  25515. */
  25516. Scene.prototype.setTransformMatrix = function (view, projection) {
  25517. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25518. return;
  25519. }
  25520. this._viewUpdateFlag = view.updateFlag;
  25521. this._projectionUpdateFlag = projection.updateFlag;
  25522. this._viewMatrix = view;
  25523. this._projectionMatrix = projection;
  25524. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25525. // Update frustum
  25526. if (!this._frustumPlanes) {
  25527. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25528. }
  25529. else {
  25530. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25531. }
  25532. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25533. var otherCamera = this.activeCamera._alternateCamera;
  25534. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25535. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25536. }
  25537. if (this._sceneUbo.useUbo) {
  25538. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25539. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25540. this._sceneUbo.update();
  25541. }
  25542. };
  25543. /** @ignore */
  25544. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25545. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25546. return;
  25547. }
  25548. this._alternateViewUpdateFlag = view.updateFlag;
  25549. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25550. this._alternateViewMatrix = view;
  25551. this._alternateProjectionMatrix = projection;
  25552. if (!this._alternateTransformMatrix) {
  25553. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25554. }
  25555. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25556. if (!this._alternateSceneUbo) {
  25557. this._createAlternateUbo();
  25558. }
  25559. if (this._alternateSceneUbo.useUbo) {
  25560. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25561. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25562. this._alternateSceneUbo.update();
  25563. }
  25564. };
  25565. /**
  25566. * Gets the uniform buffer used to store scene data
  25567. * @returns a UniformBuffer
  25568. */
  25569. Scene.prototype.getSceneUniformBuffer = function () {
  25570. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25571. };
  25572. /**
  25573. * Gets an unique (relatively to the current scene) Id
  25574. * @returns an unique number for the scene
  25575. */
  25576. Scene.prototype.getUniqueId = function () {
  25577. var result = Scene._uniqueIdCounter;
  25578. Scene._uniqueIdCounter++;
  25579. return result;
  25580. };
  25581. /**
  25582. * Add a mesh to the list of scene's meshes
  25583. * @param newMesh defines the mesh to add
  25584. */
  25585. Scene.prototype.addMesh = function (newMesh) {
  25586. this.meshes.push(newMesh);
  25587. //notify the collision coordinator
  25588. if (this.collisionCoordinator) {
  25589. this.collisionCoordinator.onMeshAdded(newMesh);
  25590. }
  25591. newMesh._resyncLightSources();
  25592. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25593. };
  25594. /**
  25595. * Remove a mesh for the list of scene's meshes
  25596. * @param toRemove defines the mesh to remove
  25597. * @returns the index where the mesh was in the mesh list
  25598. */
  25599. Scene.prototype.removeMesh = function (toRemove) {
  25600. var index = this.meshes.indexOf(toRemove);
  25601. if (index !== -1) {
  25602. // Remove from the scene if mesh found
  25603. this.meshes.splice(index, 1);
  25604. }
  25605. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25606. return index;
  25607. };
  25608. /**
  25609. * Add a transform node to the list of scene's transform nodes
  25610. * @param newTransformNode defines the transform node to add
  25611. */
  25612. Scene.prototype.addTransformNode = function (newTransformNode) {
  25613. this.transformNodes.push(newTransformNode);
  25614. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25615. };
  25616. /**
  25617. * Remove a transform node for the list of scene's transform nodes
  25618. * @param toRemove defines the transform node to remove
  25619. * @returns the index where the transform node was in the transform node list
  25620. */
  25621. Scene.prototype.removeTransformNode = function (toRemove) {
  25622. var index = this.transformNodes.indexOf(toRemove);
  25623. if (index !== -1) {
  25624. // Remove from the scene if found
  25625. this.transformNodes.splice(index, 1);
  25626. }
  25627. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25628. return index;
  25629. };
  25630. /**
  25631. * Remove a skeleton for the list of scene's skeletons
  25632. * @param toRemove defines the skeleton to remove
  25633. * @returns the index where the skeleton was in the skeleton list
  25634. */
  25635. Scene.prototype.removeSkeleton = function (toRemove) {
  25636. var index = this.skeletons.indexOf(toRemove);
  25637. if (index !== -1) {
  25638. // Remove from the scene if found
  25639. this.skeletons.splice(index, 1);
  25640. }
  25641. return index;
  25642. };
  25643. /**
  25644. * Remove a morph target for the list of scene's morph targets
  25645. * @param toRemove defines the morph target to remove
  25646. * @returns the index where the morph target was in the morph target list
  25647. */
  25648. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25649. var index = this.morphTargetManagers.indexOf(toRemove);
  25650. if (index !== -1) {
  25651. // Remove from the scene if found
  25652. this.morphTargetManagers.splice(index, 1);
  25653. }
  25654. return index;
  25655. };
  25656. /**
  25657. * Remove a light for the list of scene's lights
  25658. * @param toRemove defines the light to remove
  25659. * @returns the index where the light was in the light list
  25660. */
  25661. Scene.prototype.removeLight = function (toRemove) {
  25662. var index = this.lights.indexOf(toRemove);
  25663. if (index !== -1) {
  25664. // Remove from meshes
  25665. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25666. var mesh = _a[_i];
  25667. mesh._removeLightSource(toRemove);
  25668. }
  25669. // Remove from the scene if mesh found
  25670. this.lights.splice(index, 1);
  25671. this.sortLightsByPriority();
  25672. }
  25673. this.onLightRemovedObservable.notifyObservers(toRemove);
  25674. return index;
  25675. };
  25676. /**
  25677. * Remove a camera for the list of scene's cameras
  25678. * @param toRemove defines the camera to remove
  25679. * @returns the index where the camera was in the camera list
  25680. */
  25681. Scene.prototype.removeCamera = function (toRemove) {
  25682. var index = this.cameras.indexOf(toRemove);
  25683. if (index !== -1) {
  25684. // Remove from the scene if mesh found
  25685. this.cameras.splice(index, 1);
  25686. }
  25687. // Remove from activeCameras
  25688. var index2 = this.activeCameras.indexOf(toRemove);
  25689. if (index2 !== -1) {
  25690. // Remove from the scene if mesh found
  25691. this.activeCameras.splice(index2, 1);
  25692. }
  25693. // Reset the activeCamera
  25694. if (this.activeCamera === toRemove) {
  25695. if (this.cameras.length > 0) {
  25696. this.activeCamera = this.cameras[0];
  25697. }
  25698. else {
  25699. this.activeCamera = null;
  25700. }
  25701. }
  25702. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25703. return index;
  25704. };
  25705. /**
  25706. * Remove a particle system for the list of scene's particle systems
  25707. * @param toRemove defines the particle system to remove
  25708. * @returns the index where the particle system was in the particle system list
  25709. */
  25710. Scene.prototype.removeParticleSystem = function (toRemove) {
  25711. var index = this.particleSystems.indexOf(toRemove);
  25712. if (index !== -1) {
  25713. this.particleSystems.splice(index, 1);
  25714. }
  25715. return index;
  25716. };
  25717. /**
  25718. * Remove a animation for the list of scene's animations
  25719. * @param toRemove defines the animation to remove
  25720. * @returns the index where the animation was in the animation list
  25721. */
  25722. Scene.prototype.removeAnimation = function (toRemove) {
  25723. var index = this.animations.indexOf(toRemove);
  25724. if (index !== -1) {
  25725. this.animations.splice(index, 1);
  25726. }
  25727. return index;
  25728. };
  25729. /**
  25730. * Removes the given animation group from this scene.
  25731. * @param toRemove The animation group to remove
  25732. * @returns The index of the removed animation group
  25733. */
  25734. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25735. var index = this.animationGroups.indexOf(toRemove);
  25736. if (index !== -1) {
  25737. this.animationGroups.splice(index, 1);
  25738. }
  25739. return index;
  25740. };
  25741. /**
  25742. * Removes the given multi-material from this scene.
  25743. * @param toRemove The multi-material to remove
  25744. * @returns The index of the removed multi-material
  25745. */
  25746. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25747. var index = this.multiMaterials.indexOf(toRemove);
  25748. if (index !== -1) {
  25749. this.multiMaterials.splice(index, 1);
  25750. }
  25751. return index;
  25752. };
  25753. /**
  25754. * Removes the given material from this scene.
  25755. * @param toRemove The material to remove
  25756. * @returns The index of the removed material
  25757. */
  25758. Scene.prototype.removeMaterial = function (toRemove) {
  25759. var index = this.materials.indexOf(toRemove);
  25760. if (index !== -1) {
  25761. this.materials.splice(index, 1);
  25762. }
  25763. return index;
  25764. };
  25765. /**
  25766. * Removes the given lens flare system from this scene.
  25767. * @param toRemove The lens flare system to remove
  25768. * @returns The index of the removed lens flare system
  25769. */
  25770. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25771. var index = this.lensFlareSystems.indexOf(toRemove);
  25772. if (index !== -1) {
  25773. this.lensFlareSystems.splice(index, 1);
  25774. }
  25775. return index;
  25776. };
  25777. /**
  25778. * Removes the given action manager from this scene.
  25779. * @param toRemove The action manager to remove
  25780. * @returns The index of the removed action manager
  25781. */
  25782. Scene.prototype.removeActionManager = function (toRemove) {
  25783. var index = this._actionManagers.indexOf(toRemove);
  25784. if (index !== -1) {
  25785. this._actionManagers.splice(index, 1);
  25786. }
  25787. return index;
  25788. };
  25789. /**
  25790. * Removes the given effect layer from this scene.
  25791. * @param toRemove defines the effect layer to remove
  25792. * @returns the index of the removed effect layer
  25793. */
  25794. Scene.prototype.removeEffectLayer = function (toRemove) {
  25795. var index = this.effectLayers.indexOf(toRemove);
  25796. if (index !== -1) {
  25797. this.effectLayers.splice(index, 1);
  25798. }
  25799. return index;
  25800. };
  25801. /**
  25802. * Removes the given texture from this scene.
  25803. * @param toRemove The texture to remove
  25804. * @returns The index of the removed texture
  25805. */
  25806. Scene.prototype.removeTexture = function (toRemove) {
  25807. var index = this.textures.indexOf(toRemove);
  25808. if (index !== -1) {
  25809. this.textures.splice(index, 1);
  25810. }
  25811. return index;
  25812. };
  25813. /**
  25814. * Adds the given light to this scene
  25815. * @param newLight The light to add
  25816. */
  25817. Scene.prototype.addLight = function (newLight) {
  25818. this.lights.push(newLight);
  25819. this.sortLightsByPriority();
  25820. // Add light to all meshes (To support if the light is removed and then readded)
  25821. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25822. var mesh = _a[_i];
  25823. if (mesh._lightSources.indexOf(newLight) === -1) {
  25824. mesh._lightSources.push(newLight);
  25825. mesh._resyncLightSources();
  25826. }
  25827. }
  25828. this.onNewLightAddedObservable.notifyObservers(newLight);
  25829. };
  25830. /**
  25831. * Sorts the list list based on light priorities
  25832. */
  25833. Scene.prototype.sortLightsByPriority = function () {
  25834. if (this.requireLightSorting) {
  25835. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25836. }
  25837. };
  25838. /**
  25839. * Adds the given camera to this scene
  25840. * @param newCamera The camera to add
  25841. */
  25842. Scene.prototype.addCamera = function (newCamera) {
  25843. this.cameras.push(newCamera);
  25844. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25845. };
  25846. /**
  25847. * Adds the given skeleton to this scene
  25848. * @param newSkeleton The skeleton to add
  25849. */
  25850. Scene.prototype.addSkeleton = function (newSkeleton) {
  25851. this.skeletons.push(newSkeleton);
  25852. };
  25853. /**
  25854. * Adds the given particle system to this scene
  25855. * @param newParticleSystem The particle system to add
  25856. */
  25857. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25858. this.particleSystems.push(newParticleSystem);
  25859. };
  25860. /**
  25861. * Adds the given animation to this scene
  25862. * @param newAnimation The animation to add
  25863. */
  25864. Scene.prototype.addAnimation = function (newAnimation) {
  25865. this.animations.push(newAnimation);
  25866. };
  25867. /**
  25868. * Adds the given animation group to this scene.
  25869. * @param newAnimationGroup The animation group to add
  25870. */
  25871. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25872. this.animationGroups.push(newAnimationGroup);
  25873. };
  25874. /**
  25875. * Adds the given multi-material to this scene
  25876. * @param newMultiMaterial The multi-material to add
  25877. */
  25878. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25879. this.multiMaterials.push(newMultiMaterial);
  25880. };
  25881. /**
  25882. * Adds the given material to this scene
  25883. * @param newMaterial The material to add
  25884. */
  25885. Scene.prototype.addMaterial = function (newMaterial) {
  25886. this.materials.push(newMaterial);
  25887. };
  25888. /**
  25889. * Adds the given morph target to this scene
  25890. * @param newMorphTargetManager The morph target to add
  25891. */
  25892. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25893. this.morphTargetManagers.push(newMorphTargetManager);
  25894. };
  25895. /**
  25896. * Adds the given geometry to this scene
  25897. * @param newGeometry The geometry to add
  25898. */
  25899. Scene.prototype.addGeometry = function (newGeometry) {
  25900. this._geometries.push(newGeometry);
  25901. };
  25902. /**
  25903. * Adds the given lens flare system to this scene
  25904. * @param newLensFlareSystem The lens flare system to add
  25905. */
  25906. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25907. this.lensFlareSystems.push(newLensFlareSystem);
  25908. };
  25909. /**
  25910. * Adds the given effect layer to this scene
  25911. * @param newEffectLayer defines the effect layer to add
  25912. */
  25913. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25914. this.effectLayers.push(newEffectLayer);
  25915. };
  25916. /**
  25917. * Adds the given action manager to this scene
  25918. * @param newActionManager The action manager to add
  25919. */
  25920. Scene.prototype.addActionManager = function (newActionManager) {
  25921. this._actionManagers.push(newActionManager);
  25922. };
  25923. /**
  25924. * Adds the given texture to this scene.
  25925. * @param newTexture The texture to add
  25926. */
  25927. Scene.prototype.addTexture = function (newTexture) {
  25928. this.textures.push(newTexture);
  25929. };
  25930. /**
  25931. * Switch active camera
  25932. * @param newCamera defines the new active camera
  25933. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25934. */
  25935. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25936. if (attachControl === void 0) { attachControl = true; }
  25937. var canvas = this._engine.getRenderingCanvas();
  25938. if (!canvas) {
  25939. return;
  25940. }
  25941. if (this.activeCamera) {
  25942. this.activeCamera.detachControl(canvas);
  25943. }
  25944. this.activeCamera = newCamera;
  25945. if (attachControl) {
  25946. newCamera.attachControl(canvas);
  25947. }
  25948. };
  25949. /**
  25950. * sets the active camera of the scene using its ID
  25951. * @param id defines the camera's ID
  25952. * @return the new active camera or null if none found.
  25953. */
  25954. Scene.prototype.setActiveCameraByID = function (id) {
  25955. var camera = this.getCameraByID(id);
  25956. if (camera) {
  25957. this.activeCamera = camera;
  25958. return camera;
  25959. }
  25960. return null;
  25961. };
  25962. /**
  25963. * sets the active camera of the scene using its name
  25964. * @param name defines the camera's name
  25965. * @returns the new active camera or null if none found.
  25966. */
  25967. Scene.prototype.setActiveCameraByName = function (name) {
  25968. var camera = this.getCameraByName(name);
  25969. if (camera) {
  25970. this.activeCamera = camera;
  25971. return camera;
  25972. }
  25973. return null;
  25974. };
  25975. /**
  25976. * get an animation group using its name
  25977. * @param name defines the material's name
  25978. * @return the animation group or null if none found.
  25979. */
  25980. Scene.prototype.getAnimationGroupByName = function (name) {
  25981. for (var index = 0; index < this.animationGroups.length; index++) {
  25982. if (this.animationGroups[index].name === name) {
  25983. return this.animationGroups[index];
  25984. }
  25985. }
  25986. return null;
  25987. };
  25988. /**
  25989. * get a material using its id
  25990. * @param id defines the material's ID
  25991. * @return the material or null if none found.
  25992. */
  25993. Scene.prototype.getMaterialByID = function (id) {
  25994. for (var index = 0; index < this.materials.length; index++) {
  25995. if (this.materials[index].id === id) {
  25996. return this.materials[index];
  25997. }
  25998. }
  25999. return null;
  26000. };
  26001. /**
  26002. * Gets a material using its name
  26003. * @param name defines the material's name
  26004. * @return the material or null if none found.
  26005. */
  26006. Scene.prototype.getMaterialByName = function (name) {
  26007. for (var index = 0; index < this.materials.length; index++) {
  26008. if (this.materials[index].name === name) {
  26009. return this.materials[index];
  26010. }
  26011. }
  26012. return null;
  26013. };
  26014. /**
  26015. * Gets a lens flare system using its name
  26016. * @param name defines the name to look for
  26017. * @returns the lens flare system or null if not found
  26018. */
  26019. Scene.prototype.getLensFlareSystemByName = function (name) {
  26020. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26021. if (this.lensFlareSystems[index].name === name) {
  26022. return this.lensFlareSystems[index];
  26023. }
  26024. }
  26025. return null;
  26026. };
  26027. /**
  26028. * Gets a lens flare system using its id
  26029. * @param id defines the id to look for
  26030. * @returns the lens flare system or null if not found
  26031. */
  26032. Scene.prototype.getLensFlareSystemByID = function (id) {
  26033. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26034. if (this.lensFlareSystems[index].id === id) {
  26035. return this.lensFlareSystems[index];
  26036. }
  26037. }
  26038. return null;
  26039. };
  26040. /**
  26041. * Gets a camera using its id
  26042. * @param id defines the id to look for
  26043. * @returns the camera or null if not found
  26044. */
  26045. Scene.prototype.getCameraByID = function (id) {
  26046. for (var index = 0; index < this.cameras.length; index++) {
  26047. if (this.cameras[index].id === id) {
  26048. return this.cameras[index];
  26049. }
  26050. }
  26051. return null;
  26052. };
  26053. /**
  26054. * Gets a camera using its unique id
  26055. * @param uniqueId defines the unique id to look for
  26056. * @returns the camera or null if not found
  26057. */
  26058. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26059. for (var index = 0; index < this.cameras.length; index++) {
  26060. if (this.cameras[index].uniqueId === uniqueId) {
  26061. return this.cameras[index];
  26062. }
  26063. }
  26064. return null;
  26065. };
  26066. /**
  26067. * Gets a camera using its name
  26068. * @param name defines the camera's name
  26069. * @return the camera or null if none found.
  26070. */
  26071. Scene.prototype.getCameraByName = function (name) {
  26072. for (var index = 0; index < this.cameras.length; index++) {
  26073. if (this.cameras[index].name === name) {
  26074. return this.cameras[index];
  26075. }
  26076. }
  26077. return null;
  26078. };
  26079. /**
  26080. * Gets a bone using its id
  26081. * @param id defines the bone's id
  26082. * @return the bone or null if not found
  26083. */
  26084. Scene.prototype.getBoneByID = function (id) {
  26085. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26086. var skeleton = this.skeletons[skeletonIndex];
  26087. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26088. if (skeleton.bones[boneIndex].id === id) {
  26089. return skeleton.bones[boneIndex];
  26090. }
  26091. }
  26092. }
  26093. return null;
  26094. };
  26095. /**
  26096. * Gets a bone using its id
  26097. * @param name defines the bone's name
  26098. * @return the bone or null if not found
  26099. */
  26100. Scene.prototype.getBoneByName = function (name) {
  26101. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26102. var skeleton = this.skeletons[skeletonIndex];
  26103. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26104. if (skeleton.bones[boneIndex].name === name) {
  26105. return skeleton.bones[boneIndex];
  26106. }
  26107. }
  26108. }
  26109. return null;
  26110. };
  26111. /**
  26112. * Gets a light node using its name
  26113. * @param name defines the the light's name
  26114. * @return the light or null if none found.
  26115. */
  26116. Scene.prototype.getLightByName = function (name) {
  26117. for (var index = 0; index < this.lights.length; index++) {
  26118. if (this.lights[index].name === name) {
  26119. return this.lights[index];
  26120. }
  26121. }
  26122. return null;
  26123. };
  26124. /**
  26125. * Gets a light node using its id
  26126. * @param id defines the light's id
  26127. * @return the light or null if none found.
  26128. */
  26129. Scene.prototype.getLightByID = function (id) {
  26130. for (var index = 0; index < this.lights.length; index++) {
  26131. if (this.lights[index].id === id) {
  26132. return this.lights[index];
  26133. }
  26134. }
  26135. return null;
  26136. };
  26137. /**
  26138. * Gets a light node using its scene-generated unique ID
  26139. * @param uniqueId defines the light's unique id
  26140. * @return the light or null if none found.
  26141. */
  26142. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26143. for (var index = 0; index < this.lights.length; index++) {
  26144. if (this.lights[index].uniqueId === uniqueId) {
  26145. return this.lights[index];
  26146. }
  26147. }
  26148. return null;
  26149. };
  26150. /**
  26151. * Gets a particle system by id
  26152. * @param id defines the particle system id
  26153. * @return the corresponding system or null if none found
  26154. */
  26155. Scene.prototype.getParticleSystemByID = function (id) {
  26156. for (var index = 0; index < this.particleSystems.length; index++) {
  26157. if (this.particleSystems[index].id === id) {
  26158. return this.particleSystems[index];
  26159. }
  26160. }
  26161. return null;
  26162. };
  26163. /**
  26164. * Gets a geometry using its ID
  26165. * @param id defines the geometry's id
  26166. * @return the geometry or null if none found.
  26167. */
  26168. Scene.prototype.getGeometryByID = function (id) {
  26169. for (var index = 0; index < this._geometries.length; index++) {
  26170. if (this._geometries[index].id === id) {
  26171. return this._geometries[index];
  26172. }
  26173. }
  26174. return null;
  26175. };
  26176. /**
  26177. * Add a new geometry to this scene
  26178. * @param geometry defines the geometry to be added to the scene.
  26179. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26180. * @return a boolean defining if the geometry was added or not
  26181. */
  26182. Scene.prototype.pushGeometry = function (geometry, force) {
  26183. if (!force && this.getGeometryByID(geometry.id)) {
  26184. return false;
  26185. }
  26186. this._geometries.push(geometry);
  26187. //notify the collision coordinator
  26188. if (this.collisionCoordinator) {
  26189. this.collisionCoordinator.onGeometryAdded(geometry);
  26190. }
  26191. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26192. return true;
  26193. };
  26194. /**
  26195. * Removes an existing geometry
  26196. * @param geometry defines the geometry to be removed from the scene
  26197. * @return a boolean defining if the geometry was removed or not
  26198. */
  26199. Scene.prototype.removeGeometry = function (geometry) {
  26200. var index = this._geometries.indexOf(geometry);
  26201. if (index > -1) {
  26202. this._geometries.splice(index, 1);
  26203. //notify the collision coordinator
  26204. if (this.collisionCoordinator) {
  26205. this.collisionCoordinator.onGeometryDeleted(geometry);
  26206. }
  26207. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26208. return true;
  26209. }
  26210. return false;
  26211. };
  26212. /**
  26213. * Gets the list of geometries attached to the scene
  26214. * @returns an array of Geometry
  26215. */
  26216. Scene.prototype.getGeometries = function () {
  26217. return this._geometries;
  26218. };
  26219. /**
  26220. * Gets the first added mesh found of a given ID
  26221. * @param id defines the id to search for
  26222. * @return the mesh found or null if not found at all
  26223. */
  26224. Scene.prototype.getMeshByID = function (id) {
  26225. for (var index = 0; index < this.meshes.length; index++) {
  26226. if (this.meshes[index].id === id) {
  26227. return this.meshes[index];
  26228. }
  26229. }
  26230. return null;
  26231. };
  26232. /**
  26233. * Gets a list of meshes using their id
  26234. * @param id defines the id to search for
  26235. * @returns a list of meshes
  26236. */
  26237. Scene.prototype.getMeshesByID = function (id) {
  26238. return this.meshes.filter(function (m) {
  26239. return m.id === id;
  26240. });
  26241. };
  26242. /**
  26243. * Gets the first added transform node found of a given ID
  26244. * @param id defines the id to search for
  26245. * @return the found transform node or null if not found at all.
  26246. */
  26247. Scene.prototype.getTransformNodeByID = function (id) {
  26248. for (var index = 0; index < this.transformNodes.length; index++) {
  26249. if (this.transformNodes[index].id === id) {
  26250. return this.transformNodes[index];
  26251. }
  26252. }
  26253. return null;
  26254. };
  26255. /**
  26256. * Gets a list of transform nodes using their id
  26257. * @param id defines the id to search for
  26258. * @returns a list of transform nodes
  26259. */
  26260. Scene.prototype.getTransformNodesByID = function (id) {
  26261. return this.transformNodes.filter(function (m) {
  26262. return m.id === id;
  26263. });
  26264. };
  26265. /**
  26266. * Gets a mesh with its auto-generated unique id
  26267. * @param uniqueId defines the unique id to search for
  26268. * @return the found mesh or null if not found at all.
  26269. */
  26270. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26271. for (var index = 0; index < this.meshes.length; index++) {
  26272. if (this.meshes[index].uniqueId === uniqueId) {
  26273. return this.meshes[index];
  26274. }
  26275. }
  26276. return null;
  26277. };
  26278. /**
  26279. * Gets a the last added mesh using a given id
  26280. * @param id defines the id to search for
  26281. * @return the found mesh or null if not found at all.
  26282. */
  26283. Scene.prototype.getLastMeshByID = function (id) {
  26284. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26285. if (this.meshes[index].id === id) {
  26286. return this.meshes[index];
  26287. }
  26288. }
  26289. return null;
  26290. };
  26291. /**
  26292. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26293. * @param id defines the id to search for
  26294. * @return the found node or null if not found at all
  26295. */
  26296. Scene.prototype.getLastEntryByID = function (id) {
  26297. var index;
  26298. for (index = this.meshes.length - 1; index >= 0; index--) {
  26299. if (this.meshes[index].id === id) {
  26300. return this.meshes[index];
  26301. }
  26302. }
  26303. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26304. if (this.transformNodes[index].id === id) {
  26305. return this.transformNodes[index];
  26306. }
  26307. }
  26308. for (index = this.cameras.length - 1; index >= 0; index--) {
  26309. if (this.cameras[index].id === id) {
  26310. return this.cameras[index];
  26311. }
  26312. }
  26313. for (index = this.lights.length - 1; index >= 0; index--) {
  26314. if (this.lights[index].id === id) {
  26315. return this.lights[index];
  26316. }
  26317. }
  26318. return null;
  26319. };
  26320. /**
  26321. * Gets a node (Mesh, Camera, Light) using a given id
  26322. * @param id defines the id to search for
  26323. * @return the found node or null if not found at all
  26324. */
  26325. Scene.prototype.getNodeByID = function (id) {
  26326. var mesh = this.getMeshByID(id);
  26327. if (mesh) {
  26328. return mesh;
  26329. }
  26330. var light = this.getLightByID(id);
  26331. if (light) {
  26332. return light;
  26333. }
  26334. var camera = this.getCameraByID(id);
  26335. if (camera) {
  26336. return camera;
  26337. }
  26338. var bone = this.getBoneByID(id);
  26339. return bone;
  26340. };
  26341. /**
  26342. * Gets a node (Mesh, Camera, Light) using a given name
  26343. * @param name defines the name to search for
  26344. * @return the found node or null if not found at all.
  26345. */
  26346. Scene.prototype.getNodeByName = function (name) {
  26347. var mesh = this.getMeshByName(name);
  26348. if (mesh) {
  26349. return mesh;
  26350. }
  26351. var light = this.getLightByName(name);
  26352. if (light) {
  26353. return light;
  26354. }
  26355. var camera = this.getCameraByName(name);
  26356. if (camera) {
  26357. return camera;
  26358. }
  26359. var bone = this.getBoneByName(name);
  26360. return bone;
  26361. };
  26362. /**
  26363. * Gets a mesh using a given name
  26364. * @param name defines the name to search for
  26365. * @return the found mesh or null if not found at all.
  26366. */
  26367. Scene.prototype.getMeshByName = function (name) {
  26368. for (var index = 0; index < this.meshes.length; index++) {
  26369. if (this.meshes[index].name === name) {
  26370. return this.meshes[index];
  26371. }
  26372. }
  26373. return null;
  26374. };
  26375. /**
  26376. * Gets a transform node using a given name
  26377. * @param name defines the name to search for
  26378. * @return the found transform node or null if not found at all.
  26379. */
  26380. Scene.prototype.getTransformNodeByName = function (name) {
  26381. for (var index = 0; index < this.transformNodes.length; index++) {
  26382. if (this.transformNodes[index].name === name) {
  26383. return this.transformNodes[index];
  26384. }
  26385. }
  26386. return null;
  26387. };
  26388. /**
  26389. * Gets a sound using a given name
  26390. * @param name defines the name to search for
  26391. * @return the found sound or null if not found at all.
  26392. */
  26393. Scene.prototype.getSoundByName = function (name) {
  26394. var index;
  26395. if (BABYLON.AudioEngine) {
  26396. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26397. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26398. return this.mainSoundTrack.soundCollection[index];
  26399. }
  26400. }
  26401. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26402. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26403. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26404. return this.soundTracks[sdIndex].soundCollection[index];
  26405. }
  26406. }
  26407. }
  26408. }
  26409. return null;
  26410. };
  26411. /**
  26412. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26413. * @param id defines the id to search for
  26414. * @return the found skeleton or null if not found at all.
  26415. */
  26416. Scene.prototype.getLastSkeletonByID = function (id) {
  26417. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26418. if (this.skeletons[index].id === id) {
  26419. return this.skeletons[index];
  26420. }
  26421. }
  26422. return null;
  26423. };
  26424. /**
  26425. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26426. * @param id defines the id to search for
  26427. * @return the found skeleton or null if not found at all.
  26428. */
  26429. Scene.prototype.getSkeletonById = function (id) {
  26430. for (var index = 0; index < this.skeletons.length; index++) {
  26431. if (this.skeletons[index].id === id) {
  26432. return this.skeletons[index];
  26433. }
  26434. }
  26435. return null;
  26436. };
  26437. /**
  26438. * Gets a skeleton using a given name
  26439. * @param name defines the name to search for
  26440. * @return the found skeleton or null if not found at all.
  26441. */
  26442. Scene.prototype.getSkeletonByName = function (name) {
  26443. for (var index = 0; index < this.skeletons.length; index++) {
  26444. if (this.skeletons[index].name === name) {
  26445. return this.skeletons[index];
  26446. }
  26447. }
  26448. return null;
  26449. };
  26450. /**
  26451. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26452. * @param id defines the id to search for
  26453. * @return the found morph target manager or null if not found at all.
  26454. */
  26455. Scene.prototype.getMorphTargetManagerById = function (id) {
  26456. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26457. if (this.morphTargetManagers[index].uniqueId === id) {
  26458. return this.morphTargetManagers[index];
  26459. }
  26460. }
  26461. return null;
  26462. };
  26463. /**
  26464. * Gets a boolean indicating if the given mesh is active
  26465. * @param mesh defines the mesh to look for
  26466. * @returns true if the mesh is in the active list
  26467. */
  26468. Scene.prototype.isActiveMesh = function (mesh) {
  26469. return (this._activeMeshes.indexOf(mesh) !== -1);
  26470. };
  26471. /**
  26472. * Return a the first highlight layer of the scene with a given name.
  26473. * @param name The name of the highlight layer to look for.
  26474. * @return The highlight layer if found otherwise null.
  26475. */
  26476. Scene.prototype.getHighlightLayerByName = function (name) {
  26477. for (var index = 0; index < this.effectLayers.length; index++) {
  26478. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26479. return this.effectLayers[index];
  26480. }
  26481. }
  26482. return null;
  26483. };
  26484. /**
  26485. * Return a the first highlight layer of the scene with a given name.
  26486. * @param name The name of the highlight layer to look for.
  26487. * @return The highlight layer if found otherwise null.
  26488. */
  26489. Scene.prototype.getGlowLayerByName = function (name) {
  26490. for (var index = 0; index < this.effectLayers.length; index++) {
  26491. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26492. return this.effectLayers[index];
  26493. }
  26494. }
  26495. return null;
  26496. };
  26497. Object.defineProperty(Scene.prototype, "uid", {
  26498. /**
  26499. * Return a unique id as a string which can serve as an identifier for the scene
  26500. */
  26501. get: function () {
  26502. if (!this._uid) {
  26503. this._uid = BABYLON.Tools.RandomId();
  26504. }
  26505. return this._uid;
  26506. },
  26507. enumerable: true,
  26508. configurable: true
  26509. });
  26510. /**
  26511. * Add an externaly attached data from its key.
  26512. * This method call will fail and return false, if such key already exists.
  26513. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26514. * @param key the unique key that identifies the data
  26515. * @param data the data object to associate to the key for this Engine instance
  26516. * @return true if no such key were already present and the data was added successfully, false otherwise
  26517. */
  26518. Scene.prototype.addExternalData = function (key, data) {
  26519. if (!this._externalData) {
  26520. this._externalData = new BABYLON.StringDictionary();
  26521. }
  26522. return this._externalData.add(key, data);
  26523. };
  26524. /**
  26525. * Get an externaly attached data from its key
  26526. * @param key the unique key that identifies the data
  26527. * @return the associated data, if present (can be null), or undefined if not present
  26528. */
  26529. Scene.prototype.getExternalData = function (key) {
  26530. if (!this._externalData) {
  26531. return null;
  26532. }
  26533. return this._externalData.get(key);
  26534. };
  26535. /**
  26536. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26537. * @param key the unique key that identifies the data
  26538. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26539. * @return the associated data, can be null if the factory returned null.
  26540. */
  26541. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26542. if (!this._externalData) {
  26543. this._externalData = new BABYLON.StringDictionary();
  26544. }
  26545. return this._externalData.getOrAddWithFactory(key, factory);
  26546. };
  26547. /**
  26548. * Remove an externaly attached data from the Engine instance
  26549. * @param key the unique key that identifies the data
  26550. * @return true if the data was successfully removed, false if it doesn't exist
  26551. */
  26552. Scene.prototype.removeExternalData = function (key) {
  26553. return this._externalData.remove(key);
  26554. };
  26555. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26556. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26557. if (mesh.showSubMeshesBoundingBox) {
  26558. var boundingInfo = subMesh.getBoundingInfo();
  26559. if (boundingInfo !== null && boundingInfo !== undefined) {
  26560. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26561. }
  26562. }
  26563. var material = subMesh.getMaterial();
  26564. if (material !== null && material !== undefined) {
  26565. // Render targets
  26566. if (material.getRenderTargetTextures !== undefined) {
  26567. if (this._processedMaterials.indexOf(material) === -1) {
  26568. this._processedMaterials.push(material);
  26569. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26570. }
  26571. }
  26572. // Dispatch
  26573. this._activeIndices.addCount(subMesh.indexCount, false);
  26574. this._renderingManager.dispatch(subMesh, mesh, material);
  26575. }
  26576. }
  26577. };
  26578. /**
  26579. * Clear the processed materials smart array preventing retention point in material dispose.
  26580. */
  26581. Scene.prototype.freeProcessedMaterials = function () {
  26582. this._processedMaterials.dispose();
  26583. };
  26584. /**
  26585. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26586. */
  26587. Scene.prototype.freeActiveMeshes = function () {
  26588. this._activeMeshes.dispose();
  26589. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26590. this.activeCamera._activeMeshes.dispose();
  26591. }
  26592. if (this.activeCameras) {
  26593. for (var i = 0; i < this.activeCameras.length; i++) {
  26594. var activeCamera = this.activeCameras[i];
  26595. if (activeCamera && activeCamera._activeMeshes) {
  26596. activeCamera._activeMeshes.dispose();
  26597. }
  26598. }
  26599. }
  26600. };
  26601. /**
  26602. * Clear the info related to rendering groups preventing retention points during dispose.
  26603. */
  26604. Scene.prototype.freeRenderingGroups = function () {
  26605. if (this._renderingManager) {
  26606. this._renderingManager.freeRenderingGroups();
  26607. }
  26608. if (this.textures) {
  26609. for (var i = 0; i < this.textures.length; i++) {
  26610. var texture = this.textures[i];
  26611. if (texture && texture.renderList) {
  26612. texture.freeRenderingGroups();
  26613. }
  26614. }
  26615. }
  26616. };
  26617. /** @ignore */
  26618. Scene.prototype._isInIntermediateRendering = function () {
  26619. return this._intermediateRendering;
  26620. };
  26621. /**
  26622. * Defines the current active mesh candidate provider
  26623. * @param provider defines the provider to use
  26624. */
  26625. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26626. this._activeMeshCandidateProvider = provider;
  26627. };
  26628. /**
  26629. * Gets the current active mesh candidate provider
  26630. * @returns the current active mesh candidate provider
  26631. */
  26632. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26633. return this._activeMeshCandidateProvider;
  26634. };
  26635. /**
  26636. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26637. * @returns the current scene
  26638. */
  26639. Scene.prototype.freezeActiveMeshes = function () {
  26640. if (!this.activeCamera) {
  26641. return this;
  26642. }
  26643. if (!this._frustumPlanes) {
  26644. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26645. }
  26646. this._evaluateActiveMeshes();
  26647. this._activeMeshesFrozen = true;
  26648. return this;
  26649. };
  26650. /**
  26651. * Use this function to restart evaluating active meshes on every frame
  26652. * @returns the current scene
  26653. */
  26654. Scene.prototype.unfreezeActiveMeshes = function () {
  26655. this._activeMeshesFrozen = false;
  26656. return this;
  26657. };
  26658. Scene.prototype._evaluateActiveMeshes = function () {
  26659. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26660. return;
  26661. }
  26662. if (!this.activeCamera) {
  26663. return;
  26664. }
  26665. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26666. this.activeCamera._activeMeshes.reset();
  26667. this._activeMeshes.reset();
  26668. this._renderingManager.reset();
  26669. this._processedMaterials.reset();
  26670. this._activeParticleSystems.reset();
  26671. this._activeSkeletons.reset();
  26672. this._softwareSkinnedMeshes.reset();
  26673. if (this._boundingBoxRenderer) {
  26674. this._boundingBoxRenderer.reset();
  26675. }
  26676. // Meshes
  26677. var meshes;
  26678. var len;
  26679. var checkIsEnabled = true;
  26680. // Determine mesh candidates
  26681. if (this._activeMeshCandidateProvider !== undefined) {
  26682. // Use _activeMeshCandidateProvider
  26683. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26684. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26685. if (meshes !== undefined) {
  26686. len = meshes.length;
  26687. }
  26688. else {
  26689. len = 0;
  26690. }
  26691. }
  26692. else if (this._selectionOctree !== undefined) {
  26693. // Octree
  26694. var selection = this._selectionOctree.select(this._frustumPlanes);
  26695. meshes = selection.data;
  26696. len = selection.length;
  26697. }
  26698. else {
  26699. // Full scene traversal
  26700. len = this.meshes.length;
  26701. meshes = this.meshes;
  26702. }
  26703. // Check each mesh
  26704. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26705. mesh = meshes[meshIndex];
  26706. if (mesh.isBlocked) {
  26707. continue;
  26708. }
  26709. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26710. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26711. continue;
  26712. }
  26713. mesh.computeWorldMatrix();
  26714. // Intersections
  26715. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26716. this._meshesForIntersections.pushNoDuplicate(mesh);
  26717. }
  26718. // Switch to current LOD
  26719. meshLOD = mesh.getLOD(this.activeCamera);
  26720. if (meshLOD === undefined || meshLOD === null) {
  26721. continue;
  26722. }
  26723. mesh._preActivate();
  26724. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26725. this._activeMeshes.push(mesh);
  26726. this.activeCamera._activeMeshes.push(mesh);
  26727. mesh._activate(this._renderId);
  26728. if (meshLOD !== mesh) {
  26729. meshLOD._activate(this._renderId);
  26730. }
  26731. this._activeMesh(mesh, meshLOD);
  26732. }
  26733. }
  26734. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26735. // Particle systems
  26736. if (this.particlesEnabled) {
  26737. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26738. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26739. var particleSystem = this.particleSystems[particleIndex];
  26740. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26741. continue;
  26742. }
  26743. var emitter = particleSystem.emitter;
  26744. if (!emitter.position || emitter.isEnabled()) {
  26745. this._activeParticleSystems.push(particleSystem);
  26746. particleSystem.animate();
  26747. this._renderingManager.dispatchParticles(particleSystem);
  26748. }
  26749. }
  26750. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26751. }
  26752. };
  26753. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26754. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26755. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26756. mesh.skeleton.prepare();
  26757. }
  26758. if (!mesh.computeBonesUsingShaders) {
  26759. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26760. }
  26761. }
  26762. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26763. var boundingInfo = sourceMesh.getBoundingInfo();
  26764. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26765. }
  26766. if (mesh !== undefined && mesh !== null
  26767. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26768. // Submeshes Octrees
  26769. var len;
  26770. var subMeshes;
  26771. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26772. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26773. len = intersections.length;
  26774. subMeshes = intersections.data;
  26775. }
  26776. else {
  26777. subMeshes = mesh.subMeshes;
  26778. len = subMeshes.length;
  26779. }
  26780. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26781. subMesh = subMeshes[subIndex];
  26782. this._evaluateSubMesh(subMesh, mesh);
  26783. }
  26784. }
  26785. };
  26786. /**
  26787. * Update the transform matrix to update from the current active camera
  26788. * @param force defines a boolean used to force the update even if cache is up to date
  26789. */
  26790. Scene.prototype.updateTransformMatrix = function (force) {
  26791. if (!this.activeCamera) {
  26792. return;
  26793. }
  26794. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26795. };
  26796. /**
  26797. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  26798. * @param alternateCamera defines the camera to use
  26799. */
  26800. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26801. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26802. };
  26803. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26804. if (camera && camera._skipRendering) {
  26805. return;
  26806. }
  26807. var engine = this._engine;
  26808. this.activeCamera = camera;
  26809. if (!this.activeCamera)
  26810. throw new Error("Active camera not set");
  26811. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26812. // Viewport
  26813. engine.setViewport(this.activeCamera.viewport);
  26814. // Camera
  26815. this.resetCachedMaterial();
  26816. this._renderId++;
  26817. this.updateTransformMatrix();
  26818. if (camera._alternateCamera) {
  26819. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26820. this._alternateRendering = true;
  26821. }
  26822. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26823. // Meshes
  26824. this._evaluateActiveMeshes();
  26825. // Software skinning
  26826. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26827. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26828. mesh.applySkeleton(mesh.skeleton);
  26829. }
  26830. // Render targets
  26831. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26832. var needsRestoreFrameBuffer = false;
  26833. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26834. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26835. }
  26836. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26837. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26838. }
  26839. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26840. this._intermediateRendering = true;
  26841. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26842. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26843. var renderTarget = this._renderTargets.data[renderIndex];
  26844. if (renderTarget._shouldRender()) {
  26845. this._renderId++;
  26846. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26847. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26848. }
  26849. }
  26850. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26851. this._intermediateRendering = false;
  26852. this._renderId++;
  26853. needsRestoreFrameBuffer = true; // Restore back buffer
  26854. }
  26855. // Render EffecttLayer Texture
  26856. var stencilState = this._engine.getStencilBuffer();
  26857. var renderEffects = false;
  26858. var needStencil = false;
  26859. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26860. this._intermediateRendering = true;
  26861. for (var i = 0; i < this.effectLayers.length; i++) {
  26862. var effectLayer = this.effectLayers[i];
  26863. if (effectLayer.shouldRender() &&
  26864. (!effectLayer.camera ||
  26865. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26866. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26867. renderEffects = true;
  26868. needStencil = needStencil || effectLayer.needStencil();
  26869. var renderTarget = effectLayer._mainTexture;
  26870. if (renderTarget._shouldRender()) {
  26871. this._renderId++;
  26872. renderTarget.render(false, false);
  26873. needsRestoreFrameBuffer = true;
  26874. }
  26875. }
  26876. }
  26877. this._intermediateRendering = false;
  26878. this._renderId++;
  26879. }
  26880. if (needsRestoreFrameBuffer) {
  26881. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26882. }
  26883. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26884. // Prepare Frame
  26885. this.postProcessManager._prepareFrame();
  26886. // Backgrounds
  26887. var layerIndex;
  26888. var layer;
  26889. if (this.layers.length) {
  26890. engine.setDepthBuffer(false);
  26891. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26892. layer = this.layers[layerIndex];
  26893. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26894. layer.render();
  26895. }
  26896. }
  26897. engine.setDepthBuffer(true);
  26898. }
  26899. // Activate effect Layer stencil
  26900. if (needStencil) {
  26901. this._engine.setStencilBuffer(true);
  26902. }
  26903. // Render
  26904. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26905. this._renderingManager.render(null, null, true, true);
  26906. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26907. // Restore effect Layer stencil
  26908. if (needStencil) {
  26909. this._engine.setStencilBuffer(stencilState);
  26910. }
  26911. // Bounding boxes
  26912. if (this._boundingBoxRenderer) {
  26913. this._boundingBoxRenderer.render();
  26914. }
  26915. // Lens flares
  26916. if (this.lensFlaresEnabled) {
  26917. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26918. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26919. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26920. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26921. lensFlareSystem.render();
  26922. }
  26923. }
  26924. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26925. }
  26926. // Effect Layer
  26927. if (renderEffects) {
  26928. engine.setDepthBuffer(false);
  26929. for (var i = 0; i < this.effectLayers.length; i++) {
  26930. if (this.effectLayers[i].shouldRender()) {
  26931. this.effectLayers[i].render();
  26932. }
  26933. }
  26934. engine.setDepthBuffer(true);
  26935. }
  26936. // Foregrounds
  26937. if (this.layers.length) {
  26938. engine.setDepthBuffer(false);
  26939. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26940. layer = this.layers[layerIndex];
  26941. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26942. layer.render();
  26943. }
  26944. }
  26945. engine.setDepthBuffer(true);
  26946. }
  26947. // Finalize frame
  26948. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26949. // Reset some special arrays
  26950. this._renderTargets.reset();
  26951. this._alternateRendering = false;
  26952. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26953. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26954. };
  26955. Scene.prototype._processSubCameras = function (camera) {
  26956. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26957. this._renderForCamera(camera);
  26958. return;
  26959. }
  26960. // rig cameras
  26961. for (var index = 0; index < camera._rigCameras.length; index++) {
  26962. this._renderForCamera(camera._rigCameras[index], camera);
  26963. }
  26964. this.activeCamera = camera;
  26965. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26966. };
  26967. Scene.prototype._checkIntersections = function () {
  26968. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26969. var sourceMesh = this._meshesForIntersections.data[index];
  26970. if (!sourceMesh.actionManager) {
  26971. continue;
  26972. }
  26973. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26974. var action = sourceMesh.actionManager.actions[actionIndex];
  26975. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26976. var parameters = action.getTriggerParameter();
  26977. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26978. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26979. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26980. if (areIntersecting && currentIntersectionInProgress === -1) {
  26981. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26982. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26983. sourceMesh._intersectionsInProgress.push(otherMesh);
  26984. }
  26985. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26986. sourceMesh._intersectionsInProgress.push(otherMesh);
  26987. }
  26988. }
  26989. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26990. //They intersected, and now they don't.
  26991. //is this trigger an exit trigger? execute an event.
  26992. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26993. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26994. }
  26995. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26996. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  26997. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  26998. return otherMesh === parameterMesh;
  26999. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27000. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27001. }
  27002. }
  27003. }
  27004. }
  27005. }
  27006. };
  27007. /**
  27008. * Render the scene
  27009. */
  27010. Scene.prototype.render = function () {
  27011. if (this.isDisposed) {
  27012. return;
  27013. }
  27014. this._activeParticles.fetchNewFrame();
  27015. this._totalVertices.fetchNewFrame();
  27016. this._activeIndices.fetchNewFrame();
  27017. this._activeBones.fetchNewFrame();
  27018. this._meshesForIntersections.reset();
  27019. this.resetCachedMaterial();
  27020. this.onBeforeAnimationsObservable.notifyObservers(this);
  27021. // Actions
  27022. if (this.actionManager) {
  27023. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27024. }
  27025. //Simplification Queue
  27026. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27027. this.simplificationQueue.executeNext();
  27028. }
  27029. if (this._engine.isDeterministicLockStep()) {
  27030. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27031. var defaultFPS = (60.0 / 1000.0);
  27032. var defaultFrameTime = 1000 / 60; // frame time in MS
  27033. if (this._physicsEngine) {
  27034. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27035. }
  27036. var stepsTaken = 0;
  27037. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27038. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27039. internalSteps = Math.min(internalSteps, maxSubSteps);
  27040. do {
  27041. this.onBeforeStepObservable.notifyObservers(this);
  27042. // Animations
  27043. this._animationRatio = defaultFrameTime * defaultFPS;
  27044. this._animate();
  27045. this.onAfterAnimationsObservable.notifyObservers(this);
  27046. // Physics
  27047. if (this._physicsEngine) {
  27048. this.onBeforePhysicsObservable.notifyObservers(this);
  27049. this._physicsEngine._step(defaultFrameTime / 1000);
  27050. this.onAfterPhysicsObservable.notifyObservers(this);
  27051. }
  27052. this.onAfterStepObservable.notifyObservers(this);
  27053. this._currentStepId++;
  27054. stepsTaken++;
  27055. deltaTime -= defaultFrameTime;
  27056. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27057. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27058. }
  27059. else {
  27060. // Animations
  27061. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27062. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27063. this._animate();
  27064. this.onAfterAnimationsObservable.notifyObservers(this);
  27065. // Physics
  27066. if (this._physicsEngine) {
  27067. this.onBeforePhysicsObservable.notifyObservers(this);
  27068. this._physicsEngine._step(deltaTime / 1000.0);
  27069. this.onAfterPhysicsObservable.notifyObservers(this);
  27070. }
  27071. }
  27072. // update gamepad manager
  27073. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27074. this._gamepadManager._checkGamepadsStatus();
  27075. }
  27076. // Update Cameras
  27077. if (this.activeCameras.length > 0) {
  27078. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27079. var camera = this.activeCameras[cameraIndex];
  27080. camera.update();
  27081. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27082. // rig cameras
  27083. for (var index = 0; index < camera._rigCameras.length; index++) {
  27084. camera._rigCameras[index].update();
  27085. }
  27086. }
  27087. }
  27088. }
  27089. else if (this.activeCamera) {
  27090. this.activeCamera.update();
  27091. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27092. // rig cameras
  27093. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27094. this.activeCamera._rigCameras[index].update();
  27095. }
  27096. }
  27097. }
  27098. // Before render
  27099. this.onBeforeRenderObservable.notifyObservers(this);
  27100. // Customs render targets
  27101. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27102. var engine = this.getEngine();
  27103. var currentActiveCamera = this.activeCamera;
  27104. if (this.renderTargetsEnabled) {
  27105. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27106. this._intermediateRendering = true;
  27107. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27108. var renderTarget = this.customRenderTargets[customIndex];
  27109. if (renderTarget._shouldRender()) {
  27110. this._renderId++;
  27111. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27112. if (!this.activeCamera)
  27113. throw new Error("Active camera not set");
  27114. // Viewport
  27115. engine.setViewport(this.activeCamera.viewport);
  27116. // Camera
  27117. this.updateTransformMatrix();
  27118. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27119. }
  27120. }
  27121. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27122. this._intermediateRendering = false;
  27123. this._renderId++;
  27124. }
  27125. // Restore back buffer
  27126. if (this.customRenderTargets.length > 0) {
  27127. engine.restoreDefaultFramebuffer();
  27128. }
  27129. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27130. this.activeCamera = currentActiveCamera;
  27131. // Procedural textures
  27132. if (this.proceduralTexturesEnabled) {
  27133. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27134. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27135. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27136. if (proceduralTexture._shouldRender()) {
  27137. proceduralTexture.render();
  27138. }
  27139. }
  27140. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27141. }
  27142. // Clear
  27143. if (this.autoClearDepthAndStencil || this.autoClear) {
  27144. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27145. }
  27146. // Shadows
  27147. if (this.shadowsEnabled) {
  27148. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27149. var light = this.lights[lightIndex];
  27150. var shadowGenerator = light.getShadowGenerator();
  27151. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27152. var shadowMap = (shadowGenerator.getShadowMap());
  27153. if (this.textures.indexOf(shadowMap) !== -1) {
  27154. this._renderTargets.push(shadowMap);
  27155. }
  27156. }
  27157. }
  27158. }
  27159. // Depth renderer
  27160. for (var key in this._depthRenderer) {
  27161. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27162. }
  27163. // Geometry renderer
  27164. if (this._geometryBufferRenderer) {
  27165. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27166. }
  27167. // RenderPipeline
  27168. if (this._postProcessRenderPipelineManager) {
  27169. this._postProcessRenderPipelineManager.update();
  27170. }
  27171. // Multi-cameras?
  27172. if (this.activeCameras.length > 0) {
  27173. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27174. if (cameraIndex > 0) {
  27175. this._engine.clear(null, false, true, true);
  27176. }
  27177. this._processSubCameras(this.activeCameras[cameraIndex]);
  27178. }
  27179. }
  27180. else {
  27181. if (!this.activeCamera) {
  27182. throw new Error("No camera defined");
  27183. }
  27184. this._processSubCameras(this.activeCamera);
  27185. }
  27186. // Intersection checks
  27187. this._checkIntersections();
  27188. // Update the audio listener attached to the camera
  27189. if (BABYLON.AudioEngine) {
  27190. this._updateAudioParameters();
  27191. }
  27192. // After render
  27193. if (this.afterRender) {
  27194. this.afterRender();
  27195. }
  27196. this.onAfterRenderObservable.notifyObservers(this);
  27197. // Cleaning
  27198. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27199. var data = this._toBeDisposed.data[index];
  27200. if (data) {
  27201. data.dispose();
  27202. }
  27203. this._toBeDisposed[index] = null;
  27204. }
  27205. this._toBeDisposed.reset();
  27206. if (this.dumpNextRenderTargets) {
  27207. this.dumpNextRenderTargets = false;
  27208. }
  27209. this._activeBones.addCount(0, true);
  27210. this._activeIndices.addCount(0, true);
  27211. this._activeParticles.addCount(0, true);
  27212. };
  27213. Scene.prototype._updateAudioParameters = function () {
  27214. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27215. return;
  27216. }
  27217. var listeningCamera;
  27218. var audioEngine = BABYLON.Engine.audioEngine;
  27219. if (this.activeCameras.length > 0) {
  27220. listeningCamera = this.activeCameras[0];
  27221. }
  27222. else {
  27223. listeningCamera = this.activeCamera;
  27224. }
  27225. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27226. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27227. // for VR cameras
  27228. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27229. listeningCamera = listeningCamera.rigCameras[0];
  27230. }
  27231. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27232. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27233. cameraDirection.normalize();
  27234. // To avoid some errors on GearVR
  27235. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27236. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27237. }
  27238. var i;
  27239. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27240. var sound = this.mainSoundTrack.soundCollection[i];
  27241. if (sound.useCustomAttenuation) {
  27242. sound.updateDistanceFromListener();
  27243. }
  27244. }
  27245. for (i = 0; i < this.soundTracks.length; i++) {
  27246. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27247. sound = this.soundTracks[i].soundCollection[j];
  27248. if (sound.useCustomAttenuation) {
  27249. sound.updateDistanceFromListener();
  27250. }
  27251. }
  27252. }
  27253. }
  27254. };
  27255. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27256. // Audio
  27257. /**
  27258. * Gets or sets if audio support is enabled
  27259. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27260. */
  27261. get: function () {
  27262. return this._audioEnabled;
  27263. },
  27264. set: function (value) {
  27265. this._audioEnabled = value;
  27266. if (BABYLON.AudioEngine) {
  27267. if (this._audioEnabled) {
  27268. this._enableAudio();
  27269. }
  27270. else {
  27271. this._disableAudio();
  27272. }
  27273. }
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. Scene.prototype._disableAudio = function () {
  27279. var i;
  27280. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27281. this.mainSoundTrack.soundCollection[i].pause();
  27282. }
  27283. for (i = 0; i < this.soundTracks.length; i++) {
  27284. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27285. this.soundTracks[i].soundCollection[j].pause();
  27286. }
  27287. }
  27288. };
  27289. Scene.prototype._enableAudio = function () {
  27290. var i;
  27291. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27292. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27293. this.mainSoundTrack.soundCollection[i].play();
  27294. }
  27295. }
  27296. for (i = 0; i < this.soundTracks.length; i++) {
  27297. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27298. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27299. this.soundTracks[i].soundCollection[j].play();
  27300. }
  27301. }
  27302. }
  27303. };
  27304. Object.defineProperty(Scene.prototype, "headphone", {
  27305. /**
  27306. * Gets or sets if audio will be output to headphones
  27307. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27308. */
  27309. get: function () {
  27310. return this._headphone;
  27311. },
  27312. set: function (value) {
  27313. this._headphone = value;
  27314. if (BABYLON.AudioEngine) {
  27315. if (this._headphone) {
  27316. this._switchAudioModeForHeadphones();
  27317. }
  27318. else {
  27319. this._switchAudioModeForNormalSpeakers();
  27320. }
  27321. }
  27322. },
  27323. enumerable: true,
  27324. configurable: true
  27325. });
  27326. Scene.prototype._switchAudioModeForHeadphones = function () {
  27327. this.mainSoundTrack.switchPanningModelToHRTF();
  27328. for (var i = 0; i < this.soundTracks.length; i++) {
  27329. this.soundTracks[i].switchPanningModelToHRTF();
  27330. }
  27331. };
  27332. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27333. this.mainSoundTrack.switchPanningModelToEqualPower();
  27334. for (var i = 0; i < this.soundTracks.length; i++) {
  27335. this.soundTracks[i].switchPanningModelToEqualPower();
  27336. }
  27337. };
  27338. /**
  27339. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27340. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27341. * @returns the created depth renderer
  27342. */
  27343. Scene.prototype.enableDepthRenderer = function (camera) {
  27344. camera = camera || this.activeCamera;
  27345. if (!camera) {
  27346. throw "No camera available to enable depth renderer";
  27347. }
  27348. if (!this._depthRenderer[camera.id]) {
  27349. var textureType = 0;
  27350. if (this._engine.getCaps().textureHalfFloatRender) {
  27351. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27352. }
  27353. else if (this._engine.getCaps().textureFloatRender) {
  27354. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27355. }
  27356. else {
  27357. throw "Depth renderer does not support int texture type";
  27358. }
  27359. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27360. }
  27361. return this._depthRenderer[camera.id];
  27362. };
  27363. /**
  27364. * Disables a depth renderer for a given camera
  27365. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27366. */
  27367. Scene.prototype.disableDepthRenderer = function (camera) {
  27368. camera = camera || this.activeCamera;
  27369. if (!camera || !this._depthRenderer[camera.id]) {
  27370. return;
  27371. }
  27372. this._depthRenderer[camera.id].dispose();
  27373. delete this._depthRenderer[camera.id];
  27374. };
  27375. /**
  27376. * Enables a GeometryBufferRender and associates it with the scene
  27377. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27378. * @returns the GeometryBufferRenderer
  27379. */
  27380. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27381. if (ratio === void 0) { ratio = 1; }
  27382. if (this._geometryBufferRenderer) {
  27383. return this._geometryBufferRenderer;
  27384. }
  27385. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27386. if (!this._geometryBufferRenderer.isSupported) {
  27387. this._geometryBufferRenderer = null;
  27388. }
  27389. return this._geometryBufferRenderer;
  27390. };
  27391. /**
  27392. * Disables the GeometryBufferRender associated with the scene
  27393. */
  27394. Scene.prototype.disableGeometryBufferRenderer = function () {
  27395. if (!this._geometryBufferRenderer) {
  27396. return;
  27397. }
  27398. this._geometryBufferRenderer.dispose();
  27399. this._geometryBufferRenderer = null;
  27400. };
  27401. /**
  27402. * Freeze all materials
  27403. * A frozen material will not be updatable but should be faster to render
  27404. */
  27405. Scene.prototype.freezeMaterials = function () {
  27406. for (var i = 0; i < this.materials.length; i++) {
  27407. this.materials[i].freeze();
  27408. }
  27409. };
  27410. /**
  27411. * Unfreeze all materials
  27412. * A frozen material will not be updatable but should be faster to render
  27413. */
  27414. Scene.prototype.unfreezeMaterials = function () {
  27415. for (var i = 0; i < this.materials.length; i++) {
  27416. this.materials[i].unfreeze();
  27417. }
  27418. };
  27419. /**
  27420. * Releases all held ressources
  27421. */
  27422. Scene.prototype.dispose = function () {
  27423. this.beforeRender = null;
  27424. this.afterRender = null;
  27425. this.skeletons = [];
  27426. this.morphTargetManagers = [];
  27427. this.importedMeshesFiles = new Array();
  27428. this.stopAllAnimations();
  27429. this.resetCachedMaterial();
  27430. for (var key in this._depthRenderer) {
  27431. this._depthRenderer[key].dispose();
  27432. }
  27433. if (this._gamepadManager) {
  27434. this._gamepadManager.dispose();
  27435. this._gamepadManager = null;
  27436. }
  27437. // Smart arrays
  27438. if (this.activeCamera) {
  27439. this.activeCamera._activeMeshes.dispose();
  27440. this.activeCamera = null;
  27441. }
  27442. this._activeMeshes.dispose();
  27443. this._renderingManager.dispose();
  27444. this._processedMaterials.dispose();
  27445. this._activeParticleSystems.dispose();
  27446. this._activeSkeletons.dispose();
  27447. this._softwareSkinnedMeshes.dispose();
  27448. this._renderTargets.dispose();
  27449. this._registeredForLateAnimationBindings.dispose();
  27450. if (this._boundingBoxRenderer) {
  27451. this._boundingBoxRenderer.dispose();
  27452. }
  27453. this._meshesForIntersections.dispose();
  27454. this._toBeDisposed.dispose();
  27455. // Abort active requests
  27456. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27457. var request = _a[_i];
  27458. request.abort();
  27459. }
  27460. // Debug layer
  27461. if (this._debugLayer) {
  27462. this._debugLayer.hide();
  27463. }
  27464. // Events
  27465. this.onDisposeObservable.notifyObservers(this);
  27466. this.onDisposeObservable.clear();
  27467. this.onBeforeRenderObservable.clear();
  27468. this.onAfterRenderObservable.clear();
  27469. this.onBeforeRenderTargetsRenderObservable.clear();
  27470. this.onAfterRenderTargetsRenderObservable.clear();
  27471. this.onAfterStepObservable.clear();
  27472. this.onBeforeStepObservable.clear();
  27473. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27474. this.onAfterActiveMeshesEvaluationObservable.clear();
  27475. this.onBeforeParticlesRenderingObservable.clear();
  27476. this.onAfterParticlesRenderingObservable.clear();
  27477. this.onBeforeSpritesRenderingObservable.clear();
  27478. this.onAfterSpritesRenderingObservable.clear();
  27479. this.onBeforeDrawPhaseObservable.clear();
  27480. this.onAfterDrawPhaseObservable.clear();
  27481. this.onBeforePhysicsObservable.clear();
  27482. this.onAfterPhysicsObservable.clear();
  27483. this.onBeforeAnimationsObservable.clear();
  27484. this.onAfterAnimationsObservable.clear();
  27485. this.onDataLoadedObservable.clear();
  27486. this.detachControl();
  27487. // Release sounds & sounds tracks
  27488. if (BABYLON.AudioEngine) {
  27489. this.disposeSounds();
  27490. }
  27491. // VR Helper
  27492. if (this.VRHelper) {
  27493. this.VRHelper.dispose();
  27494. }
  27495. // Detach cameras
  27496. var canvas = this._engine.getRenderingCanvas();
  27497. if (canvas) {
  27498. var index;
  27499. for (index = 0; index < this.cameras.length; index++) {
  27500. this.cameras[index].detachControl(canvas);
  27501. }
  27502. }
  27503. // Release animation groups
  27504. while (this.animationGroups.length) {
  27505. this.animationGroups[0].dispose();
  27506. }
  27507. // Release lights
  27508. while (this.lights.length) {
  27509. this.lights[0].dispose();
  27510. }
  27511. // Release meshes
  27512. while (this.meshes.length) {
  27513. this.meshes[0].dispose(true);
  27514. }
  27515. while (this.transformNodes.length) {
  27516. this.removeTransformNode(this.transformNodes[0]);
  27517. }
  27518. // Release cameras
  27519. while (this.cameras.length) {
  27520. this.cameras[0].dispose();
  27521. }
  27522. // Release materials
  27523. if (this.defaultMaterial) {
  27524. this.defaultMaterial.dispose();
  27525. }
  27526. while (this.multiMaterials.length) {
  27527. this.multiMaterials[0].dispose();
  27528. }
  27529. while (this.materials.length) {
  27530. this.materials[0].dispose();
  27531. }
  27532. // Release particles
  27533. while (this.particleSystems.length) {
  27534. this.particleSystems[0].dispose();
  27535. }
  27536. // Release sprites
  27537. while (this.spriteManagers.length) {
  27538. this.spriteManagers[0].dispose();
  27539. }
  27540. // Release postProcesses
  27541. while (this.postProcesses.length) {
  27542. this.postProcesses[0].dispose();
  27543. }
  27544. // Release layers
  27545. while (this.layers.length) {
  27546. this.layers[0].dispose();
  27547. }
  27548. while (this.effectLayers.length) {
  27549. this.effectLayers[0].dispose();
  27550. }
  27551. // Release textures
  27552. while (this.textures.length) {
  27553. this.textures[0].dispose();
  27554. }
  27555. // Release UBO
  27556. this._sceneUbo.dispose();
  27557. if (this._alternateSceneUbo) {
  27558. this._alternateSceneUbo.dispose();
  27559. }
  27560. // Post-processes
  27561. this.postProcessManager.dispose();
  27562. if (this._postProcessRenderPipelineManager) {
  27563. this._postProcessRenderPipelineManager.dispose();
  27564. }
  27565. // Physics
  27566. if (this._physicsEngine) {
  27567. this.disablePhysicsEngine();
  27568. }
  27569. // Remove from engine
  27570. index = this._engine.scenes.indexOf(this);
  27571. if (index > -1) {
  27572. this._engine.scenes.splice(index, 1);
  27573. }
  27574. this._engine.wipeCaches(true);
  27575. this._isDisposed = true;
  27576. };
  27577. Object.defineProperty(Scene.prototype, "isDisposed", {
  27578. /**
  27579. * Gets if the scene is already disposed
  27580. */
  27581. get: function () {
  27582. return this._isDisposed;
  27583. },
  27584. enumerable: true,
  27585. configurable: true
  27586. });
  27587. /**
  27588. * Releases sounds & soundtracks
  27589. */
  27590. Scene.prototype.disposeSounds = function () {
  27591. if (!this._mainSoundTrack) {
  27592. return;
  27593. }
  27594. this.mainSoundTrack.dispose();
  27595. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27596. this.soundTracks[scIndex].dispose();
  27597. }
  27598. };
  27599. // Octrees
  27600. /**
  27601. * Get the world extend vectors with an optional filter
  27602. *
  27603. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27604. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27605. */
  27606. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27607. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27608. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27609. filterPredicate = filterPredicate || (function () { return true; });
  27610. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27611. mesh.computeWorldMatrix(true);
  27612. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27613. return;
  27614. }
  27615. var boundingInfo = mesh.getBoundingInfo();
  27616. var minBox = boundingInfo.boundingBox.minimumWorld;
  27617. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27618. BABYLON.Tools.CheckExtends(minBox, min, max);
  27619. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27620. });
  27621. return {
  27622. min: min,
  27623. max: max
  27624. };
  27625. };
  27626. /**
  27627. * Creates or updates the octree used to boost selection (picking)
  27628. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27629. * @param maxCapacity defines the maximum capacity per leaf
  27630. * @param maxDepth defines the maximum depth of the octree
  27631. * @returns an octree of AbstractMesh
  27632. */
  27633. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27634. if (maxCapacity === void 0) { maxCapacity = 64; }
  27635. if (maxDepth === void 0) { maxDepth = 2; }
  27636. if (!this._selectionOctree) {
  27637. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27638. }
  27639. var worldExtends = this.getWorldExtends();
  27640. // Update octree
  27641. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27642. return this._selectionOctree;
  27643. };
  27644. // Picking
  27645. /**
  27646. * Creates a ray that can be used to pick in the scene
  27647. * @param x defines the x coordinate of the origin (on-screen)
  27648. * @param y defines the y coordinate of the origin (on-screen)
  27649. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27650. * @param camera defines the camera to use for the picking
  27651. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27652. * @returns a Ray
  27653. */
  27654. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27655. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27656. var result = BABYLON.Ray.Zero();
  27657. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27658. return result;
  27659. };
  27660. /**
  27661. * Creates a ray that can be used to pick in the scene
  27662. * @param x defines the x coordinate of the origin (on-screen)
  27663. * @param y defines the y coordinate of the origin (on-screen)
  27664. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27665. * @param result defines the ray where to store the picking ray
  27666. * @param camera defines the camera to use for the picking
  27667. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27668. * @returns the current scene
  27669. */
  27670. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27671. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27672. var engine = this._engine;
  27673. if (!camera) {
  27674. if (!this.activeCamera)
  27675. throw new Error("Active camera not set");
  27676. camera = this.activeCamera;
  27677. }
  27678. var cameraViewport = camera.viewport;
  27679. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27680. // Moving coordinates to local viewport world
  27681. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27682. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27683. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27684. return this;
  27685. };
  27686. /**
  27687. * Creates a ray that can be used to pick in the scene
  27688. * @param x defines the x coordinate of the origin (on-screen)
  27689. * @param y defines the y coordinate of the origin (on-screen)
  27690. * @param camera defines the camera to use for the picking
  27691. * @returns a Ray
  27692. */
  27693. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27694. var result = BABYLON.Ray.Zero();
  27695. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27696. return result;
  27697. };
  27698. /**
  27699. * Creates a ray that can be used to pick in the scene
  27700. * @param x defines the x coordinate of the origin (on-screen)
  27701. * @param y defines the y coordinate of the origin (on-screen)
  27702. * @param result defines the ray where to store the picking ray
  27703. * @param camera defines the camera to use for the picking
  27704. * @returns the current scene
  27705. */
  27706. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27707. if (!BABYLON.PickingInfo) {
  27708. return this;
  27709. }
  27710. var engine = this._engine;
  27711. if (!camera) {
  27712. if (!this.activeCamera)
  27713. throw new Error("Active camera not set");
  27714. camera = this.activeCamera;
  27715. }
  27716. var cameraViewport = camera.viewport;
  27717. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27718. var identity = BABYLON.Matrix.Identity();
  27719. // Moving coordinates to local viewport world
  27720. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27721. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27722. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27723. return this;
  27724. };
  27725. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27726. if (!BABYLON.PickingInfo) {
  27727. return null;
  27728. }
  27729. var pickingInfo = null;
  27730. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27731. var mesh = this.meshes[meshIndex];
  27732. if (predicate) {
  27733. if (!predicate(mesh)) {
  27734. continue;
  27735. }
  27736. }
  27737. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27738. continue;
  27739. }
  27740. var world = mesh.getWorldMatrix();
  27741. var ray = rayFunction(world);
  27742. var result = mesh.intersects(ray, fastCheck);
  27743. if (!result || !result.hit)
  27744. continue;
  27745. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27746. continue;
  27747. pickingInfo = result;
  27748. if (fastCheck) {
  27749. break;
  27750. }
  27751. }
  27752. return pickingInfo || new BABYLON.PickingInfo();
  27753. };
  27754. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27755. if (!BABYLON.PickingInfo) {
  27756. return null;
  27757. }
  27758. var pickingInfos = new Array();
  27759. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27760. var mesh = this.meshes[meshIndex];
  27761. if (predicate) {
  27762. if (!predicate(mesh)) {
  27763. continue;
  27764. }
  27765. }
  27766. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27767. continue;
  27768. }
  27769. var world = mesh.getWorldMatrix();
  27770. var ray = rayFunction(world);
  27771. var result = mesh.intersects(ray, false);
  27772. if (!result || !result.hit)
  27773. continue;
  27774. pickingInfos.push(result);
  27775. }
  27776. return pickingInfos;
  27777. };
  27778. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27779. if (!BABYLON.PickingInfo) {
  27780. return null;
  27781. }
  27782. var pickingInfo = null;
  27783. if (!camera) {
  27784. if (!this.activeCamera) {
  27785. return null;
  27786. }
  27787. camera = this.activeCamera;
  27788. }
  27789. if (this.spriteManagers.length > 0) {
  27790. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27791. var spriteManager = this.spriteManagers[spriteIndex];
  27792. if (!spriteManager.isPickable) {
  27793. continue;
  27794. }
  27795. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27796. if (!result || !result.hit)
  27797. continue;
  27798. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27799. continue;
  27800. pickingInfo = result;
  27801. if (fastCheck) {
  27802. break;
  27803. }
  27804. }
  27805. }
  27806. return pickingInfo || new BABYLON.PickingInfo();
  27807. };
  27808. /** Launch a ray to try to pick a mesh in the scene
  27809. * @param x position on screen
  27810. * @param y position on screen
  27811. * @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
  27812. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27813. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27814. * @returns a PickingInfo
  27815. */
  27816. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27817. var _this = this;
  27818. if (!BABYLON.PickingInfo) {
  27819. return null;
  27820. }
  27821. return this._internalPick(function (world) {
  27822. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27823. return _this._tempPickingRay;
  27824. }, predicate, fastCheck);
  27825. };
  27826. /** Launch a ray to try to pick a sprite in the scene
  27827. * @param x position on screen
  27828. * @param y position on screen
  27829. * @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
  27830. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27831. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27832. * @returns a PickingInfo
  27833. */
  27834. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27835. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27836. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27837. };
  27838. /** Use the given ray to pick a mesh in the scene
  27839. * @param ray The ray to use to pick meshes
  27840. * @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
  27841. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27842. * @returns a PickingInfo
  27843. */
  27844. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27845. var _this = this;
  27846. return this._internalPick(function (world) {
  27847. if (!_this._pickWithRayInverseMatrix) {
  27848. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27849. }
  27850. world.invertToRef(_this._pickWithRayInverseMatrix);
  27851. if (!_this._cachedRayForTransform) {
  27852. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27853. }
  27854. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27855. return _this._cachedRayForTransform;
  27856. }, predicate, fastCheck);
  27857. };
  27858. /**
  27859. * Launch a ray to try to pick a mesh in the scene
  27860. * @param x X position on screen
  27861. * @param y Y position on screen
  27862. * @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
  27863. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27864. * @returns an array of PickingInfo
  27865. */
  27866. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27867. var _this = this;
  27868. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27869. };
  27870. /**
  27871. * Launch a ray to try to pick a mesh in the scene
  27872. * @param ray Ray to use
  27873. * @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
  27874. * @returns an array of PickingInfo
  27875. */
  27876. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27877. var _this = this;
  27878. return this._internalMultiPick(function (world) {
  27879. if (!_this._pickWithRayInverseMatrix) {
  27880. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27881. }
  27882. world.invertToRef(_this._pickWithRayInverseMatrix);
  27883. if (!_this._cachedRayForTransform) {
  27884. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27885. }
  27886. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27887. return _this._cachedRayForTransform;
  27888. }, predicate);
  27889. };
  27890. /**
  27891. * Force the value of meshUnderPointer
  27892. * @param mesh defines the mesh to use
  27893. */
  27894. Scene.prototype.setPointerOverMesh = function (mesh) {
  27895. if (this._pointerOverMesh === mesh) {
  27896. return;
  27897. }
  27898. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27899. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27900. }
  27901. this._pointerOverMesh = mesh;
  27902. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27903. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27904. }
  27905. };
  27906. /**
  27907. * Gets the mesh under the pointer
  27908. * @returns a Mesh or null if no mesh is under the pointer
  27909. */
  27910. Scene.prototype.getPointerOverMesh = function () {
  27911. return this._pointerOverMesh;
  27912. };
  27913. /**
  27914. * Force the sprite under the pointer
  27915. * @param sprite defines the sprite to use
  27916. */
  27917. Scene.prototype.setPointerOverSprite = function (sprite) {
  27918. if (this._pointerOverSprite === sprite) {
  27919. return;
  27920. }
  27921. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27922. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27923. }
  27924. this._pointerOverSprite = sprite;
  27925. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27926. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27927. }
  27928. };
  27929. /**
  27930. * Gets the sprite under the pointer
  27931. * @returns a Sprite or null if no sprite is under the pointer
  27932. */
  27933. Scene.prototype.getPointerOverSprite = function () {
  27934. return this._pointerOverSprite;
  27935. };
  27936. // Physics
  27937. /**
  27938. * Gets the current physics engine
  27939. * @returns a PhysicsEngine or null if none attached
  27940. */
  27941. Scene.prototype.getPhysicsEngine = function () {
  27942. return this._physicsEngine;
  27943. };
  27944. /**
  27945. * Enables physics to the current scene
  27946. * @param gravity defines the scene's gravity for the physics engine
  27947. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27948. * @return a boolean indicating if the physics engine was initialized
  27949. */
  27950. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27951. if (gravity === void 0) { gravity = null; }
  27952. if (this._physicsEngine) {
  27953. return true;
  27954. }
  27955. try {
  27956. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27957. return true;
  27958. }
  27959. catch (e) {
  27960. BABYLON.Tools.Error(e.message);
  27961. return false;
  27962. }
  27963. };
  27964. /**
  27965. * Disables and disposes the physics engine associated with the scene
  27966. */
  27967. Scene.prototype.disablePhysicsEngine = function () {
  27968. if (!this._physicsEngine) {
  27969. return;
  27970. }
  27971. this._physicsEngine.dispose();
  27972. this._physicsEngine = null;
  27973. };
  27974. /**
  27975. * Gets a boolean indicating if there is an active physics engine
  27976. * @returns a boolean indicating if there is an active physics engine
  27977. */
  27978. Scene.prototype.isPhysicsEnabled = function () {
  27979. return this._physicsEngine !== undefined;
  27980. };
  27981. /**
  27982. * Deletes a physics compound impostor
  27983. * @param compound defines the compound to delete
  27984. */
  27985. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27986. var mesh = compound.parts[0].mesh;
  27987. if (mesh.physicsImpostor) {
  27988. mesh.physicsImpostor.dispose( /*true*/);
  27989. mesh.physicsImpostor = null;
  27990. }
  27991. };
  27992. // Misc.
  27993. /** @ignore */
  27994. Scene.prototype._rebuildGeometries = function () {
  27995. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27996. var geometry = _a[_i];
  27997. geometry._rebuild();
  27998. }
  27999. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28000. var mesh = _c[_b];
  28001. mesh._rebuild();
  28002. }
  28003. if (this.postProcessManager) {
  28004. this.postProcessManager._rebuild();
  28005. }
  28006. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28007. var layer = _e[_d];
  28008. layer._rebuild();
  28009. }
  28010. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28011. var effectLayer = _g[_f];
  28012. effectLayer._rebuild();
  28013. }
  28014. if (this._boundingBoxRenderer) {
  28015. this._boundingBoxRenderer._rebuild();
  28016. }
  28017. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28018. var system = _j[_h];
  28019. system.rebuild();
  28020. }
  28021. if (this._postProcessRenderPipelineManager) {
  28022. this._postProcessRenderPipelineManager._rebuild();
  28023. }
  28024. };
  28025. /** @ignore */
  28026. Scene.prototype._rebuildTextures = function () {
  28027. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28028. var texture = _a[_i];
  28029. texture._rebuild();
  28030. }
  28031. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28032. };
  28033. /**
  28034. * Creates a default light for the scene.
  28035. * @param replace Whether to replace the existing lights in the scene.
  28036. */
  28037. Scene.prototype.createDefaultLight = function (replace) {
  28038. if (replace === void 0) { replace = false; }
  28039. // Dispose existing light in replace mode.
  28040. if (replace) {
  28041. if (this.lights) {
  28042. for (var i = 0; i < this.lights.length; i++) {
  28043. this.lights[i].dispose();
  28044. }
  28045. }
  28046. }
  28047. // Light
  28048. if (this.lights.length === 0) {
  28049. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28050. }
  28051. };
  28052. /**
  28053. * Creates a default camera for the scene.
  28054. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28055. * @param replace Whether to replace the existing active camera in the scene.
  28056. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28057. */
  28058. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28059. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28060. if (replace === void 0) { replace = false; }
  28061. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28062. // Dispose existing camera in replace mode.
  28063. if (replace) {
  28064. if (this.activeCamera) {
  28065. this.activeCamera.dispose();
  28066. this.activeCamera = null;
  28067. }
  28068. }
  28069. // Camera
  28070. if (!this.activeCamera) {
  28071. var worldExtends = this.getWorldExtends();
  28072. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28073. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28074. var camera;
  28075. var radius = worldSize.length() * 1.5;
  28076. // empty scene scenario!
  28077. if (!isFinite(radius)) {
  28078. radius = 1;
  28079. worldCenter.copyFromFloats(0, 0, 0);
  28080. }
  28081. if (createArcRotateCamera) {
  28082. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28083. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28084. arcRotateCamera.wheelPrecision = 100 / radius;
  28085. camera = arcRotateCamera;
  28086. }
  28087. else {
  28088. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28089. freeCamera.setTarget(worldCenter);
  28090. camera = freeCamera;
  28091. }
  28092. camera.minZ = radius * 0.01;
  28093. camera.maxZ = radius * 1000;
  28094. camera.speed = radius * 0.2;
  28095. this.activeCamera = camera;
  28096. var canvas = this.getEngine().getRenderingCanvas();
  28097. if (attachCameraControls && canvas) {
  28098. camera.attachControl(canvas);
  28099. }
  28100. }
  28101. };
  28102. /**
  28103. * Creates a default camera and a default light
  28104. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28105. * @param replace defines if the camera and/or light will replace the existing ones
  28106. * @param attachCameraControls defines if attachControl will be called on the new camera
  28107. */
  28108. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28109. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28110. if (replace === void 0) { replace = false; }
  28111. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28112. this.createDefaultLight(replace);
  28113. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28114. };
  28115. /**
  28116. * Creates a new sky box
  28117. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28118. * @param environmentTexture defines the texture to use as environment texture
  28119. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28120. * @param scale defines the overall scale of the skybox
  28121. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28122. * @returns a new mesh holding the sky box
  28123. */
  28124. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28125. if (pbr === void 0) { pbr = false; }
  28126. if (scale === void 0) { scale = 1000; }
  28127. if (blur === void 0) { blur = 0; }
  28128. if (environmentTexture) {
  28129. this.environmentTexture = environmentTexture;
  28130. }
  28131. if (!this.environmentTexture) {
  28132. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28133. return null;
  28134. }
  28135. // Skybox
  28136. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28137. if (pbr) {
  28138. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28139. hdrSkyboxMaterial.backFaceCulling = false;
  28140. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28141. if (hdrSkyboxMaterial.reflectionTexture) {
  28142. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28143. }
  28144. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28145. hdrSkyboxMaterial.disableLighting = true;
  28146. hdrSkyboxMaterial.twoSidedLighting = true;
  28147. hdrSkybox.infiniteDistance = true;
  28148. hdrSkybox.material = hdrSkyboxMaterial;
  28149. }
  28150. else {
  28151. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28152. skyboxMaterial.backFaceCulling = false;
  28153. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28154. if (skyboxMaterial.reflectionTexture) {
  28155. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28156. }
  28157. skyboxMaterial.disableLighting = true;
  28158. hdrSkybox.infiniteDistance = true;
  28159. hdrSkybox.material = skyboxMaterial;
  28160. }
  28161. return hdrSkybox;
  28162. };
  28163. /**
  28164. * Creates a new environment
  28165. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28166. * @param options defines the options you can use to configure the environment
  28167. * @returns the new EnvironmentHelper
  28168. */
  28169. Scene.prototype.createDefaultEnvironment = function (options) {
  28170. if (BABYLON.EnvironmentHelper) {
  28171. return new BABYLON.EnvironmentHelper(options, this);
  28172. }
  28173. return null;
  28174. };
  28175. /**
  28176. * Creates a new VREXperienceHelper
  28177. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28178. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28179. * @returns a new VREXperienceHelper
  28180. */
  28181. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28182. if (webVROptions === void 0) { webVROptions = {}; }
  28183. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28184. };
  28185. // Tags
  28186. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28187. if (tagsQuery === undefined) {
  28188. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28189. return list;
  28190. }
  28191. var listByTags = [];
  28192. forEach = forEach || (function (item) { return; });
  28193. for (var i in list) {
  28194. var item = list[i];
  28195. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28196. listByTags.push(item);
  28197. forEach(item);
  28198. }
  28199. }
  28200. return listByTags;
  28201. };
  28202. /**
  28203. * Get a list of meshes by tags
  28204. * @param tagsQuery defines the tags query to use
  28205. * @param forEach defines a predicate used to filter results
  28206. * @returns an array of Mesh
  28207. */
  28208. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28209. return this._getByTags(this.meshes, tagsQuery, forEach);
  28210. };
  28211. /**
  28212. * Get a list of cameras by tags
  28213. * @param tagsQuery defines the tags query to use
  28214. * @param forEach defines a predicate used to filter results
  28215. * @returns an array of Camera
  28216. */
  28217. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28218. return this._getByTags(this.cameras, tagsQuery, forEach);
  28219. };
  28220. /**
  28221. * Get a list of lights by tags
  28222. * @param tagsQuery defines the tags query to use
  28223. * @param forEach defines a predicate used to filter results
  28224. * @returns an array of Light
  28225. */
  28226. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28227. return this._getByTags(this.lights, tagsQuery, forEach);
  28228. };
  28229. /**
  28230. * Get a list of materials by tags
  28231. * @param tagsQuery defines the tags query to use
  28232. * @param forEach defines a predicate used to filter results
  28233. * @returns an array of Material
  28234. */
  28235. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28236. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28237. };
  28238. /**
  28239. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28240. * This allowed control for front to back rendering or reversly depending of the special needs.
  28241. *
  28242. * @param renderingGroupId The rendering group id corresponding to its index
  28243. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28244. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28245. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28246. */
  28247. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28248. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28249. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28250. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28251. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28252. };
  28253. /**
  28254. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28255. *
  28256. * @param renderingGroupId The rendering group id corresponding to its index
  28257. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28258. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28259. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28260. */
  28261. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28262. if (depth === void 0) { depth = true; }
  28263. if (stencil === void 0) { stencil = true; }
  28264. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28265. };
  28266. /**
  28267. * Will flag all materials as dirty to trigger new shader compilation
  28268. * @param flag defines the flag used to specify which material part must be marked as dirty
  28269. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28270. */
  28271. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28272. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28273. var material = _a[_i];
  28274. if (predicate && !predicate(material)) {
  28275. continue;
  28276. }
  28277. material.markAsDirty(flag);
  28278. }
  28279. };
  28280. /** @ignore */
  28281. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28282. var _this = this;
  28283. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28284. this._activeRequests.push(request);
  28285. request.onCompleteObservable.add(function (request) {
  28286. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28287. });
  28288. return request;
  28289. };
  28290. /** @ignore */
  28291. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28292. var _this = this;
  28293. return new Promise(function (resolve, reject) {
  28294. _this._loadFile(url, function (data) {
  28295. resolve(data);
  28296. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28297. reject(exception);
  28298. });
  28299. });
  28300. };
  28301. // Statics
  28302. Scene._FOGMODE_NONE = 0;
  28303. Scene._FOGMODE_EXP = 1;
  28304. Scene._FOGMODE_EXP2 = 2;
  28305. Scene._FOGMODE_LINEAR = 3;
  28306. Scene._uniqueIdCounter = 0;
  28307. /**
  28308. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28309. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28310. */
  28311. Scene.MinDeltaTime = 1.0;
  28312. /**
  28313. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28314. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28315. */
  28316. Scene.MaxDeltaTime = 1000.0;
  28317. /** The distance in pixel that you have to move to prevent some events */
  28318. Scene.DragMovementThreshold = 10; // in pixels
  28319. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28320. Scene.LongPressDelay = 500; // in milliseconds
  28321. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28322. Scene.DoubleClickDelay = 300; // in milliseconds
  28323. /** If you need to check double click without raising a single click at first click, enable this flag */
  28324. Scene.ExclusiveDoubleClickMode = false;
  28325. return Scene;
  28326. }());
  28327. BABYLON.Scene = Scene;
  28328. })(BABYLON || (BABYLON = {}));
  28329. //# sourceMappingURL=babylon.scene.js.map
  28330. var BABYLON;
  28331. (function (BABYLON) {
  28332. /**
  28333. * Set of assets to keep when moving a scene into an asset container.
  28334. */
  28335. var KeepAssets = /** @class */ (function () {
  28336. function KeepAssets() {
  28337. /**
  28338. * Cameras to keep.
  28339. */
  28340. this.cameras = new Array();
  28341. /**
  28342. * Lights to keep.
  28343. */
  28344. this.lights = new Array();
  28345. /**
  28346. * Meshes to keep.
  28347. */
  28348. this.meshes = new Array();
  28349. /**
  28350. * Skeletons to keep.
  28351. */
  28352. this.skeletons = new Array();
  28353. /**
  28354. * ParticleSystems to keep.
  28355. */
  28356. this.particleSystems = new Array();
  28357. /**
  28358. * Animations to keep.
  28359. */
  28360. this.animations = new Array();
  28361. /**
  28362. * AnimationGroups to keep.
  28363. */
  28364. this.animationGroups = new Array();
  28365. /**
  28366. * MultiMaterials to keep.
  28367. */
  28368. this.multiMaterials = new Array();
  28369. /**
  28370. * Materials to keep.
  28371. */
  28372. this.materials = new Array();
  28373. /**
  28374. * MorphTargetManagers to keep.
  28375. */
  28376. this.morphTargetManagers = new Array();
  28377. /**
  28378. * Geometries to keep.
  28379. */
  28380. this.geometries = new Array();
  28381. /**
  28382. * TransformNodes to keep.
  28383. */
  28384. this.transformNodes = new Array();
  28385. /**
  28386. * LensFlareSystems to keep.
  28387. */
  28388. this.lensFlareSystems = new Array();
  28389. /**
  28390. * ShadowGenerators to keep.
  28391. */
  28392. this.shadowGenerators = new Array();
  28393. /**
  28394. * ActionManagers to keep.
  28395. */
  28396. this.actionManagers = new Array();
  28397. /**
  28398. * Sounds to keep.
  28399. */
  28400. this.sounds = new Array();
  28401. /**
  28402. * Textures to keep.
  28403. */
  28404. this.textures = new Array();
  28405. /**
  28406. * Effect layers to keep.
  28407. */
  28408. this.effectLayers = new Array();
  28409. }
  28410. return KeepAssets;
  28411. }());
  28412. BABYLON.KeepAssets = KeepAssets;
  28413. /**
  28414. * Container with a set of assets that can be added or removed from a scene.
  28415. */
  28416. var AssetContainer = /** @class */ (function () {
  28417. /**
  28418. * Instantiates an AssetContainer.
  28419. * @param scene The scene the AssetContainer belongs to.
  28420. */
  28421. function AssetContainer(scene) {
  28422. // Objects
  28423. /**
  28424. * Cameras populated in the container.
  28425. */
  28426. this.cameras = new Array();
  28427. /**
  28428. * Lights populated in the container.
  28429. */
  28430. this.lights = new Array();
  28431. /**
  28432. * Meshes populated in the container.
  28433. */
  28434. this.meshes = new Array();
  28435. /**
  28436. * Skeletons populated in the container.
  28437. */
  28438. this.skeletons = new Array();
  28439. /**
  28440. * ParticleSystems populated in the container.
  28441. */
  28442. this.particleSystems = new Array();
  28443. /**
  28444. * Animations populated in the container.
  28445. */
  28446. this.animations = new Array();
  28447. /**
  28448. * AnimationGroups populated in the container.
  28449. */
  28450. this.animationGroups = new Array();
  28451. /**
  28452. * MultiMaterials populated in the container.
  28453. */
  28454. this.multiMaterials = new Array();
  28455. /**
  28456. * Materials populated in the container.
  28457. */
  28458. this.materials = new Array();
  28459. /**
  28460. * MorphTargetManagers populated in the container.
  28461. */
  28462. this.morphTargetManagers = new Array();
  28463. /**
  28464. * Geometries populated in the container.
  28465. */
  28466. this.geometries = new Array();
  28467. /**
  28468. * TransformNodes populated in the container.
  28469. */
  28470. this.transformNodes = new Array();
  28471. /**
  28472. * LensFlareSystems populated in the container.
  28473. */
  28474. this.lensFlareSystems = new Array();
  28475. /**
  28476. * ShadowGenerators populated in the container.
  28477. */
  28478. this.shadowGenerators = new Array();
  28479. /**
  28480. * ActionManagers populated in the container.
  28481. */
  28482. this.actionManagers = new Array();
  28483. /**
  28484. * Sounds populated in the container.
  28485. */
  28486. this.sounds = new Array();
  28487. /**
  28488. * Textures populated in the container.
  28489. */
  28490. this.textures = new Array();
  28491. /**
  28492. * Effect layers populated in the container.
  28493. */
  28494. this.effectLayers = new Array();
  28495. this.scene = scene;
  28496. }
  28497. /**
  28498. * Adds all the assets from the container to the scene.
  28499. */
  28500. AssetContainer.prototype.addAllToScene = function () {
  28501. var _this = this;
  28502. this.cameras.forEach(function (o) {
  28503. _this.scene.addCamera(o);
  28504. });
  28505. this.lights.forEach(function (o) {
  28506. _this.scene.addLight(o);
  28507. });
  28508. this.meshes.forEach(function (o) {
  28509. _this.scene.addMesh(o);
  28510. });
  28511. this.skeletons.forEach(function (o) {
  28512. _this.scene.addSkeleton(o);
  28513. });
  28514. this.particleSystems.forEach(function (o) {
  28515. _this.scene.addParticleSystem(o);
  28516. });
  28517. this.animations.forEach(function (o) {
  28518. _this.scene.addAnimation(o);
  28519. });
  28520. this.animationGroups.forEach(function (o) {
  28521. _this.scene.addAnimationGroup(o);
  28522. });
  28523. this.multiMaterials.forEach(function (o) {
  28524. _this.scene.addMultiMaterial(o);
  28525. });
  28526. this.materials.forEach(function (o) {
  28527. _this.scene.addMaterial(o);
  28528. });
  28529. this.morphTargetManagers.forEach(function (o) {
  28530. _this.scene.addMorphTargetManager(o);
  28531. });
  28532. this.geometries.forEach(function (o) {
  28533. _this.scene.addGeometry(o);
  28534. });
  28535. this.transformNodes.forEach(function (o) {
  28536. _this.scene.addTransformNode(o);
  28537. });
  28538. this.lensFlareSystems.forEach(function (o) {
  28539. _this.scene.addLensFlareSystem(o);
  28540. });
  28541. this.actionManagers.forEach(function (o) {
  28542. _this.scene.addActionManager(o);
  28543. });
  28544. this.sounds.forEach(function (o) {
  28545. o.play();
  28546. o.autoplay = true;
  28547. _this.scene.mainSoundTrack.AddSound(o);
  28548. });
  28549. this.textures.forEach(function (o) {
  28550. _this.scene.addTexture(o);
  28551. });
  28552. this.effectLayers.forEach(function (o) {
  28553. _this.scene.addEffectLayer(o);
  28554. });
  28555. };
  28556. /**
  28557. * Removes all the assets in the container from the scene
  28558. */
  28559. AssetContainer.prototype.removeAllFromScene = function () {
  28560. var _this = this;
  28561. this.cameras.forEach(function (o) {
  28562. _this.scene.removeCamera(o);
  28563. });
  28564. this.lights.forEach(function (o) {
  28565. _this.scene.removeLight(o);
  28566. });
  28567. this.meshes.forEach(function (o) {
  28568. _this.scene.removeMesh(o);
  28569. });
  28570. this.skeletons.forEach(function (o) {
  28571. _this.scene.removeSkeleton(o);
  28572. });
  28573. this.particleSystems.forEach(function (o) {
  28574. _this.scene.removeParticleSystem(o);
  28575. });
  28576. this.animations.forEach(function (o) {
  28577. _this.scene.removeAnimation(o);
  28578. });
  28579. this.animationGroups.forEach(function (o) {
  28580. _this.scene.removeAnimationGroup(o);
  28581. });
  28582. this.multiMaterials.forEach(function (o) {
  28583. _this.scene.removeMultiMaterial(o);
  28584. });
  28585. this.materials.forEach(function (o) {
  28586. _this.scene.removeMaterial(o);
  28587. });
  28588. this.morphTargetManagers.forEach(function (o) {
  28589. _this.scene.removeMorphTargetManager(o);
  28590. });
  28591. this.geometries.forEach(function (o) {
  28592. _this.scene.removeGeometry(o);
  28593. });
  28594. this.transformNodes.forEach(function (o) {
  28595. _this.scene.removeTransformNode(o);
  28596. });
  28597. this.lensFlareSystems.forEach(function (o) {
  28598. _this.scene.removeLensFlareSystem(o);
  28599. });
  28600. this.actionManagers.forEach(function (o) {
  28601. _this.scene.removeActionManager(o);
  28602. });
  28603. this.sounds.forEach(function (o) {
  28604. o.stop();
  28605. o.autoplay = false;
  28606. _this.scene.mainSoundTrack.RemoveSound(o);
  28607. });
  28608. this.textures.forEach(function (o) {
  28609. _this.scene.removeTexture(o);
  28610. });
  28611. this.effectLayers.forEach(function (o) {
  28612. _this.scene.removeEffectLayer(o);
  28613. });
  28614. };
  28615. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28616. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28617. var asset = sourceAssets_1[_i];
  28618. var move = true;
  28619. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28620. var keepAsset = keepAssets_1[_a];
  28621. if (asset === keepAsset) {
  28622. move = false;
  28623. break;
  28624. }
  28625. }
  28626. if (move) {
  28627. targetAssets.push(asset);
  28628. }
  28629. }
  28630. };
  28631. /**
  28632. * Removes all the assets contained in the scene and adds them to the container.
  28633. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28634. */
  28635. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28636. if (keepAssets === undefined) {
  28637. keepAssets = new KeepAssets();
  28638. }
  28639. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28640. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28641. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28642. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28643. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28644. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28645. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28646. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28647. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28648. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28649. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28650. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28651. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28652. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28653. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28654. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28655. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28656. this.removeAllFromScene();
  28657. };
  28658. return AssetContainer;
  28659. }());
  28660. BABYLON.AssetContainer = AssetContainer;
  28661. })(BABYLON || (BABYLON = {}));
  28662. //# sourceMappingURL=babylon.assetContainer.js.map
  28663. var BABYLON;
  28664. (function (BABYLON) {
  28665. var Buffer = /** @class */ (function () {
  28666. /**
  28667. * Constructor
  28668. * @param engine the engine
  28669. * @param data the data to use for this buffer
  28670. * @param updatable whether the data is updatable
  28671. * @param stride the stride (optional)
  28672. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28673. * @param instanced whether the buffer is instanced (optional)
  28674. * @param useBytes set to true if the stride in in bytes (optional)
  28675. */
  28676. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28677. if (stride === void 0) { stride = 0; }
  28678. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28679. if (instanced === void 0) { instanced = false; }
  28680. if (useBytes === void 0) { useBytes = false; }
  28681. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28682. this._engine = engine.getScene().getEngine();
  28683. }
  28684. else {
  28685. this._engine = engine;
  28686. }
  28687. this._updatable = updatable;
  28688. this._instanced = instanced;
  28689. this._data = data;
  28690. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28691. if (!postponeInternalCreation) { // by default
  28692. this.create();
  28693. }
  28694. }
  28695. /**
  28696. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28697. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28698. * @param offset defines offset in the buffer (0 by default)
  28699. * @param size defines the size in floats of attributes (position is 3 for instance)
  28700. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28701. * @param instanced defines if the vertex buffer contains indexed data
  28702. * @param useBytes defines if the offset and stride are in bytes
  28703. * @returns the new vertex buffer
  28704. */
  28705. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28706. if (useBytes === void 0) { useBytes = false; }
  28707. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28708. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28709. // a lot of these parameters are ignored as they are overriden by the buffer
  28710. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28711. };
  28712. // Properties
  28713. Buffer.prototype.isUpdatable = function () {
  28714. return this._updatable;
  28715. };
  28716. Buffer.prototype.getData = function () {
  28717. return this._data;
  28718. };
  28719. Buffer.prototype.getBuffer = function () {
  28720. return this._buffer;
  28721. };
  28722. /**
  28723. * Gets the stride in float32 units (i.e. byte stride / 4).
  28724. * May not be an integer if the byte stride is not divisible by 4.
  28725. * DEPRECATED. Use byteStride instead.
  28726. * @returns the stride in float32 units
  28727. */
  28728. Buffer.prototype.getStrideSize = function () {
  28729. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28730. };
  28731. // Methods
  28732. Buffer.prototype.create = function (data) {
  28733. if (data === void 0) { data = null; }
  28734. if (!data && this._buffer) {
  28735. return; // nothing to do
  28736. }
  28737. data = data || this._data;
  28738. if (!data) {
  28739. return;
  28740. }
  28741. if (!this._buffer) { // create buffer
  28742. if (this._updatable) {
  28743. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28744. this._data = data;
  28745. }
  28746. else {
  28747. this._buffer = this._engine.createVertexBuffer(data);
  28748. }
  28749. }
  28750. else if (this._updatable) { // update buffer
  28751. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28752. this._data = data;
  28753. }
  28754. };
  28755. Buffer.prototype._rebuild = function () {
  28756. this._buffer = null;
  28757. this.create(this._data);
  28758. };
  28759. Buffer.prototype.update = function (data) {
  28760. this.create(data);
  28761. };
  28762. /**
  28763. * Updates the data directly.
  28764. * @param data the new data
  28765. * @param offset the new offset
  28766. * @param vertexCount the vertex count (optional)
  28767. * @param useBytes set to true if the offset is in bytes
  28768. */
  28769. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28770. if (useBytes === void 0) { useBytes = false; }
  28771. if (!this._buffer) {
  28772. return;
  28773. }
  28774. if (this._updatable) { // update buffer
  28775. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28776. this._data = null;
  28777. }
  28778. };
  28779. Buffer.prototype.dispose = function () {
  28780. if (!this._buffer) {
  28781. return;
  28782. }
  28783. if (this._engine._releaseBuffer(this._buffer)) {
  28784. this._buffer = null;
  28785. }
  28786. };
  28787. return Buffer;
  28788. }());
  28789. BABYLON.Buffer = Buffer;
  28790. })(BABYLON || (BABYLON = {}));
  28791. //# sourceMappingURL=babylon.buffer.js.map
  28792. var BABYLON;
  28793. (function (BABYLON) {
  28794. var VertexBuffer = /** @class */ (function () {
  28795. /**
  28796. * Constructor
  28797. * @param engine the engine
  28798. * @param data the data to use for this vertex buffer
  28799. * @param kind the vertex buffer kind
  28800. * @param updatable whether the data is updatable
  28801. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28802. * @param stride the stride (optional)
  28803. * @param instanced whether the buffer is instanced (optional)
  28804. * @param offset the offset of the data (optional)
  28805. * @param size the number of components (optional)
  28806. * @param type the type of the component (optional)
  28807. * @param normalized whether the data contains normalized data (optional)
  28808. * @param useBytes set to true if stride and offset are in bytes (optional)
  28809. */
  28810. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28811. if (normalized === void 0) { normalized = false; }
  28812. if (useBytes === void 0) { useBytes = false; }
  28813. if (data instanceof BABYLON.Buffer) {
  28814. this._buffer = data;
  28815. this._ownsBuffer = false;
  28816. }
  28817. else {
  28818. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28819. this._ownsBuffer = true;
  28820. }
  28821. this._kind = kind;
  28822. if (type == undefined) {
  28823. var data_1 = this.getData();
  28824. this.type = VertexBuffer.FLOAT;
  28825. if (data_1 instanceof Int8Array)
  28826. this.type = VertexBuffer.BYTE;
  28827. else if (data_1 instanceof Uint8Array)
  28828. this.type = VertexBuffer.UNSIGNED_BYTE;
  28829. else if (data_1 instanceof Int16Array)
  28830. this.type = VertexBuffer.SHORT;
  28831. else if (data_1 instanceof Uint16Array)
  28832. this.type = VertexBuffer.UNSIGNED_SHORT;
  28833. else if (data_1 instanceof Int32Array)
  28834. this.type = VertexBuffer.INT;
  28835. else if (data_1 instanceof Uint32Array)
  28836. this.type = VertexBuffer.UNSIGNED_INT;
  28837. }
  28838. else {
  28839. this.type = type;
  28840. }
  28841. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28842. if (useBytes) {
  28843. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28844. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28845. this.byteOffset = offset || 0;
  28846. }
  28847. else {
  28848. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28849. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28850. this.byteOffset = (offset || 0) * typeByteLength;
  28851. }
  28852. this.normalized = normalized;
  28853. this._instanced = instanced !== undefined ? instanced : false;
  28854. this._instanceDivisor = instanced ? 1 : 0;
  28855. }
  28856. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28857. /**
  28858. * Gets or sets the instance divisor when in instanced mode
  28859. */
  28860. get: function () {
  28861. return this._instanceDivisor;
  28862. },
  28863. set: function (value) {
  28864. this._instanceDivisor = value;
  28865. if (value == 0) {
  28866. this._instanced = false;
  28867. }
  28868. else {
  28869. this._instanced = true;
  28870. }
  28871. },
  28872. enumerable: true,
  28873. configurable: true
  28874. });
  28875. VertexBuffer.prototype._rebuild = function () {
  28876. if (!this._buffer) {
  28877. return;
  28878. }
  28879. this._buffer._rebuild();
  28880. };
  28881. /**
  28882. * Returns the kind of the VertexBuffer (string).
  28883. */
  28884. VertexBuffer.prototype.getKind = function () {
  28885. return this._kind;
  28886. };
  28887. // Properties
  28888. /**
  28889. * Boolean : is the VertexBuffer updatable ?
  28890. */
  28891. VertexBuffer.prototype.isUpdatable = function () {
  28892. return this._buffer.isUpdatable();
  28893. };
  28894. /**
  28895. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28896. */
  28897. VertexBuffer.prototype.getData = function () {
  28898. return this._buffer.getData();
  28899. };
  28900. /**
  28901. * Returns the WebGLBuffer associated to the VertexBuffer.
  28902. */
  28903. VertexBuffer.prototype.getBuffer = function () {
  28904. return this._buffer.getBuffer();
  28905. };
  28906. /**
  28907. * Returns the stride as a multiple of the type byte length.
  28908. * DEPRECATED. Use byteStride instead.
  28909. */
  28910. VertexBuffer.prototype.getStrideSize = function () {
  28911. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28912. };
  28913. /**
  28914. * Returns the offset as a multiple of the type byte length.
  28915. * DEPRECATED. Use byteOffset instead.
  28916. */
  28917. VertexBuffer.prototype.getOffset = function () {
  28918. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28919. };
  28920. /**
  28921. * Returns the number of components per vertex attribute (integer).
  28922. */
  28923. VertexBuffer.prototype.getSize = function () {
  28924. return this._size;
  28925. };
  28926. /**
  28927. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28928. */
  28929. VertexBuffer.prototype.getIsInstanced = function () {
  28930. return this._instanced;
  28931. };
  28932. /**
  28933. * Returns the instancing divisor, zero for non-instanced (integer).
  28934. */
  28935. VertexBuffer.prototype.getInstanceDivisor = function () {
  28936. return this._instanceDivisor;
  28937. };
  28938. // Methods
  28939. /**
  28940. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28941. * Returns the created WebGLBuffer.
  28942. */
  28943. VertexBuffer.prototype.create = function (data) {
  28944. return this._buffer.create(data);
  28945. };
  28946. /**
  28947. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28948. * This function will create a new buffer if the current one is not updatable
  28949. * Returns the updated WebGLBuffer.
  28950. */
  28951. VertexBuffer.prototype.update = function (data) {
  28952. return this._buffer.update(data);
  28953. };
  28954. /**
  28955. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28956. * Returns the directly updated WebGLBuffer.
  28957. * @param data the new data
  28958. * @param offset the new offset
  28959. * @param useBytes set to true if the offset is in bytes
  28960. */
  28961. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28962. if (useBytes === void 0) { useBytes = false; }
  28963. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28964. };
  28965. /**
  28966. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28967. */
  28968. VertexBuffer.prototype.dispose = function () {
  28969. if (this._ownsBuffer) {
  28970. this._buffer.dispose();
  28971. }
  28972. };
  28973. /**
  28974. * Enumerates each value of this vertex buffer as numbers.
  28975. * @param count the number of values to enumerate
  28976. * @param callback the callback function called for each value
  28977. */
  28978. VertexBuffer.prototype.forEach = function (count, callback) {
  28979. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28980. };
  28981. Object.defineProperty(VertexBuffer, "PositionKind", {
  28982. get: function () {
  28983. return VertexBuffer._PositionKind;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. Object.defineProperty(VertexBuffer, "NormalKind", {
  28989. get: function () {
  28990. return VertexBuffer._NormalKind;
  28991. },
  28992. enumerable: true,
  28993. configurable: true
  28994. });
  28995. Object.defineProperty(VertexBuffer, "TangentKind", {
  28996. get: function () {
  28997. return VertexBuffer._TangentKind;
  28998. },
  28999. enumerable: true,
  29000. configurable: true
  29001. });
  29002. Object.defineProperty(VertexBuffer, "UVKind", {
  29003. get: function () {
  29004. return VertexBuffer._UVKind;
  29005. },
  29006. enumerable: true,
  29007. configurable: true
  29008. });
  29009. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29010. get: function () {
  29011. return VertexBuffer._UV2Kind;
  29012. },
  29013. enumerable: true,
  29014. configurable: true
  29015. });
  29016. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29017. get: function () {
  29018. return VertexBuffer._UV3Kind;
  29019. },
  29020. enumerable: true,
  29021. configurable: true
  29022. });
  29023. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29024. get: function () {
  29025. return VertexBuffer._UV4Kind;
  29026. },
  29027. enumerable: true,
  29028. configurable: true
  29029. });
  29030. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29031. get: function () {
  29032. return VertexBuffer._UV5Kind;
  29033. },
  29034. enumerable: true,
  29035. configurable: true
  29036. });
  29037. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29038. get: function () {
  29039. return VertexBuffer._UV6Kind;
  29040. },
  29041. enumerable: true,
  29042. configurable: true
  29043. });
  29044. Object.defineProperty(VertexBuffer, "ColorKind", {
  29045. get: function () {
  29046. return VertexBuffer._ColorKind;
  29047. },
  29048. enumerable: true,
  29049. configurable: true
  29050. });
  29051. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29052. get: function () {
  29053. return VertexBuffer._MatricesIndicesKind;
  29054. },
  29055. enumerable: true,
  29056. configurable: true
  29057. });
  29058. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29059. get: function () {
  29060. return VertexBuffer._MatricesWeightsKind;
  29061. },
  29062. enumerable: true,
  29063. configurable: true
  29064. });
  29065. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29066. get: function () {
  29067. return VertexBuffer._MatricesIndicesExtraKind;
  29068. },
  29069. enumerable: true,
  29070. configurable: true
  29071. });
  29072. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29073. get: function () {
  29074. return VertexBuffer._MatricesWeightsExtraKind;
  29075. },
  29076. enumerable: true,
  29077. configurable: true
  29078. });
  29079. /**
  29080. * Deduces the stride given a kind.
  29081. * @param kind The kind string to deduce
  29082. * @returns The deduced stride
  29083. */
  29084. VertexBuffer.DeduceStride = function (kind) {
  29085. switch (kind) {
  29086. case VertexBuffer.UVKind:
  29087. case VertexBuffer.UV2Kind:
  29088. case VertexBuffer.UV3Kind:
  29089. case VertexBuffer.UV4Kind:
  29090. case VertexBuffer.UV5Kind:
  29091. case VertexBuffer.UV6Kind:
  29092. return 2;
  29093. case VertexBuffer.NormalKind:
  29094. case VertexBuffer.PositionKind:
  29095. return 3;
  29096. case VertexBuffer.ColorKind:
  29097. case VertexBuffer.MatricesIndicesKind:
  29098. case VertexBuffer.MatricesIndicesExtraKind:
  29099. case VertexBuffer.MatricesWeightsKind:
  29100. case VertexBuffer.MatricesWeightsExtraKind:
  29101. case VertexBuffer.TangentKind:
  29102. return 4;
  29103. default:
  29104. throw new Error("Invalid kind '" + kind + "'");
  29105. }
  29106. };
  29107. /**
  29108. * Gets the byte length of the given type.
  29109. * @param type the type
  29110. * @returns the number of bytes
  29111. */
  29112. VertexBuffer.GetTypeByteLength = function (type) {
  29113. switch (type) {
  29114. case VertexBuffer.BYTE:
  29115. case VertexBuffer.UNSIGNED_BYTE:
  29116. return 1;
  29117. case VertexBuffer.SHORT:
  29118. case VertexBuffer.UNSIGNED_SHORT:
  29119. return 2;
  29120. case VertexBuffer.INT:
  29121. case VertexBuffer.FLOAT:
  29122. return 4;
  29123. default:
  29124. throw new Error("Invalid type '" + type + "'");
  29125. }
  29126. };
  29127. /**
  29128. * Enumerates each value of the given parameters as numbers.
  29129. * @param data the data to enumerate
  29130. * @param byteOffset the byte offset of the data
  29131. * @param byteStride the byte stride of the data
  29132. * @param componentCount the number of components per element
  29133. * @param componentType the type of the component
  29134. * @param count the total number of components
  29135. * @param normalized whether the data is normalized
  29136. * @param callback the callback function called for each value
  29137. */
  29138. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29139. if (data instanceof Array) {
  29140. var offset = byteOffset / 4;
  29141. var stride = byteStride / 4;
  29142. for (var index = 0; index < count; index += componentCount) {
  29143. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29144. callback(data[offset + componentIndex], index + componentIndex);
  29145. }
  29146. offset += stride;
  29147. }
  29148. }
  29149. else {
  29150. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29151. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29152. for (var index = 0; index < count; index += componentCount) {
  29153. var componentByteOffset = byteOffset;
  29154. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29155. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29156. callback(value, index + componentIndex);
  29157. componentByteOffset += componentByteLength;
  29158. }
  29159. byteOffset += byteStride;
  29160. }
  29161. }
  29162. };
  29163. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29164. switch (type) {
  29165. case VertexBuffer.BYTE: {
  29166. var value = dataView.getInt8(byteOffset);
  29167. if (normalized) {
  29168. value = (value + 0.5) / 127.5;
  29169. }
  29170. return value;
  29171. }
  29172. case VertexBuffer.UNSIGNED_BYTE: {
  29173. var value = dataView.getUint8(byteOffset);
  29174. if (normalized) {
  29175. value = value / 255;
  29176. }
  29177. return value;
  29178. }
  29179. case VertexBuffer.SHORT: {
  29180. var value = dataView.getInt16(byteOffset, true);
  29181. if (normalized) {
  29182. value = (value + 0.5) / 16383.5;
  29183. }
  29184. return value;
  29185. }
  29186. case VertexBuffer.UNSIGNED_SHORT: {
  29187. var value = dataView.getUint16(byteOffset, true);
  29188. if (normalized) {
  29189. value = value / 65535;
  29190. }
  29191. return value;
  29192. }
  29193. case VertexBuffer.FLOAT: {
  29194. return dataView.getFloat32(byteOffset, true);
  29195. }
  29196. default: {
  29197. throw new Error("Invalid component type " + type);
  29198. }
  29199. }
  29200. };
  29201. /**
  29202. * The byte type.
  29203. */
  29204. VertexBuffer.BYTE = 5120;
  29205. /**
  29206. * The unsigned byte type.
  29207. */
  29208. VertexBuffer.UNSIGNED_BYTE = 5121;
  29209. /**
  29210. * The short type.
  29211. */
  29212. VertexBuffer.SHORT = 5122;
  29213. /**
  29214. * The unsigned short type.
  29215. */
  29216. VertexBuffer.UNSIGNED_SHORT = 5123;
  29217. /**
  29218. * The integer type.
  29219. */
  29220. VertexBuffer.INT = 5124;
  29221. /**
  29222. * The unsigned integer type.
  29223. */
  29224. VertexBuffer.UNSIGNED_INT = 5125;
  29225. /**
  29226. * The float type.
  29227. */
  29228. VertexBuffer.FLOAT = 5126;
  29229. // Enums
  29230. VertexBuffer._PositionKind = "position";
  29231. VertexBuffer._NormalKind = "normal";
  29232. VertexBuffer._TangentKind = "tangent";
  29233. VertexBuffer._UVKind = "uv";
  29234. VertexBuffer._UV2Kind = "uv2";
  29235. VertexBuffer._UV3Kind = "uv3";
  29236. VertexBuffer._UV4Kind = "uv4";
  29237. VertexBuffer._UV5Kind = "uv5";
  29238. VertexBuffer._UV6Kind = "uv6";
  29239. VertexBuffer._ColorKind = "color";
  29240. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29241. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29242. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29243. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29244. return VertexBuffer;
  29245. }());
  29246. BABYLON.VertexBuffer = VertexBuffer;
  29247. })(BABYLON || (BABYLON = {}));
  29248. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29249. var BABYLON;
  29250. (function (BABYLON) {
  29251. /**
  29252. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29253. */
  29254. var DummyInternalTextureTracker = /** @class */ (function () {
  29255. function DummyInternalTextureTracker() {
  29256. /**
  29257. * Gets or set the previous tracker in the list
  29258. */
  29259. this.previous = null;
  29260. /**
  29261. * Gets or set the next tracker in the list
  29262. */
  29263. this.next = null;
  29264. }
  29265. return DummyInternalTextureTracker;
  29266. }());
  29267. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29268. })(BABYLON || (BABYLON = {}));
  29269. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29270. var BABYLON;
  29271. (function (BABYLON) {
  29272. /**
  29273. * Class used to store data associated with WebGL texture data for the engine
  29274. * This class should not be used directly
  29275. */
  29276. var InternalTexture = /** @class */ (function () {
  29277. /**
  29278. * Creates a new InternalTexture
  29279. * @param engine defines the engine to use
  29280. * @param dataSource defines the type of data that will be used
  29281. */
  29282. function InternalTexture(engine, dataSource) {
  29283. /**
  29284. * Observable called when the texture is loaded
  29285. */
  29286. this.onLoadedObservable = new BABYLON.Observable();
  29287. /**
  29288. * Gets or set the previous tracker in the list
  29289. */
  29290. this.previous = null;
  29291. /**
  29292. * Gets or set the next tracker in the list
  29293. */
  29294. this.next = null;
  29295. // Private
  29296. /** @ignore */
  29297. this._initialSlot = -1;
  29298. /** @ignore */
  29299. this._designatedSlot = -1;
  29300. /** @ignore */
  29301. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29302. /** @ignore */
  29303. this._comparisonFunction = 0;
  29304. /** @ignore */
  29305. this._references = 1;
  29306. this._engine = engine;
  29307. this._dataSource = dataSource;
  29308. this._webGLTexture = engine._createTexture();
  29309. }
  29310. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29311. /**
  29312. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29313. */
  29314. get: function () {
  29315. return this._dataSource;
  29316. },
  29317. enumerable: true,
  29318. configurable: true
  29319. });
  29320. /**
  29321. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29322. */
  29323. InternalTexture.prototype.incrementReferences = function () {
  29324. this._references++;
  29325. };
  29326. /**
  29327. * Change the size of the texture (not the size of the content)
  29328. * @param width defines the new width
  29329. * @param height defines the new height
  29330. * @param depth defines the new depth (1 by default)
  29331. */
  29332. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29333. if (depth === void 0) { depth = 1; }
  29334. this.width = width;
  29335. this.height = height;
  29336. this.depth = depth;
  29337. this.baseWidth = width;
  29338. this.baseHeight = height;
  29339. this.baseDepth = depth;
  29340. this._size = width * height * depth;
  29341. };
  29342. /** @ignore */
  29343. InternalTexture.prototype._rebuild = function () {
  29344. var _this = this;
  29345. var proxy;
  29346. this.isReady = false;
  29347. this._cachedCoordinatesMode = null;
  29348. this._cachedWrapU = null;
  29349. this._cachedWrapV = null;
  29350. this._cachedAnisotropicFilteringLevel = null;
  29351. switch (this._dataSource) {
  29352. case InternalTexture.DATASOURCE_TEMP:
  29353. return;
  29354. case InternalTexture.DATASOURCE_URL:
  29355. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29356. _this.isReady = true;
  29357. }, null, this._buffer, undefined, this.format);
  29358. proxy._swapAndDie(this);
  29359. return;
  29360. case InternalTexture.DATASOURCE_RAW:
  29361. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29362. proxy._swapAndDie(this);
  29363. this.isReady = true;
  29364. return;
  29365. case InternalTexture.DATASOURCE_RAW3D:
  29366. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29367. proxy._swapAndDie(this);
  29368. this.isReady = true;
  29369. return;
  29370. case InternalTexture.DATASOURCE_DYNAMIC:
  29371. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29372. proxy._swapAndDie(this);
  29373. // The engine will make sure to update content so no need to flag it as isReady = true
  29374. return;
  29375. case InternalTexture.DATASOURCE_RENDERTARGET:
  29376. var options = new BABYLON.RenderTargetCreationOptions();
  29377. options.generateDepthBuffer = this._generateDepthBuffer;
  29378. options.generateMipMaps = this.generateMipMaps;
  29379. options.generateStencilBuffer = this._generateStencilBuffer;
  29380. options.samplingMode = this.samplingMode;
  29381. options.type = this.type;
  29382. if (this.isCube) {
  29383. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29384. }
  29385. else {
  29386. var size = {
  29387. width: this.width,
  29388. height: this.height
  29389. };
  29390. proxy = this._engine.createRenderTargetTexture(size, options);
  29391. }
  29392. proxy._swapAndDie(this);
  29393. this.isReady = true;
  29394. return;
  29395. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29396. var depthTextureOptions = {
  29397. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29398. comparisonFunction: this._comparisonFunction,
  29399. generateStencil: this._generateStencilBuffer,
  29400. isCube: this.isCube
  29401. };
  29402. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29403. proxy._swapAndDie(this);
  29404. this.isReady = true;
  29405. return;
  29406. case InternalTexture.DATASOURCE_CUBE:
  29407. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29408. _this.isReady = true;
  29409. }, null, this.format, this._extension);
  29410. proxy._swapAndDie(this);
  29411. return;
  29412. case InternalTexture.DATASOURCE_CUBERAW:
  29413. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29414. proxy._swapAndDie(this);
  29415. this.isReady = true;
  29416. return;
  29417. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29418. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29419. if (proxy) {
  29420. proxy._swapAndDie(_this);
  29421. }
  29422. _this.isReady = true;
  29423. }, null, this.format, this._extension);
  29424. return;
  29425. }
  29426. };
  29427. InternalTexture.prototype._swapAndDie = function (target) {
  29428. target._webGLTexture = this._webGLTexture;
  29429. if (this._framebuffer) {
  29430. target._framebuffer = this._framebuffer;
  29431. }
  29432. if (this._depthStencilBuffer) {
  29433. target._depthStencilBuffer = this._depthStencilBuffer;
  29434. }
  29435. if (this._lodTextureHigh) {
  29436. if (target._lodTextureHigh) {
  29437. target._lodTextureHigh.dispose();
  29438. }
  29439. target._lodTextureHigh = this._lodTextureHigh;
  29440. }
  29441. if (this._lodTextureMid) {
  29442. if (target._lodTextureMid) {
  29443. target._lodTextureMid.dispose();
  29444. }
  29445. target._lodTextureMid = this._lodTextureMid;
  29446. }
  29447. if (this._lodTextureLow) {
  29448. if (target._lodTextureLow) {
  29449. target._lodTextureLow.dispose();
  29450. }
  29451. target._lodTextureLow = this._lodTextureLow;
  29452. }
  29453. var cache = this._engine.getLoadedTexturesCache();
  29454. var index = cache.indexOf(this);
  29455. if (index !== -1) {
  29456. cache.splice(index, 1);
  29457. }
  29458. };
  29459. /**
  29460. * Dispose the current allocated resources
  29461. */
  29462. InternalTexture.prototype.dispose = function () {
  29463. if (!this._webGLTexture) {
  29464. return;
  29465. }
  29466. this._references--;
  29467. if (this._references === 0) {
  29468. this._engine._releaseTexture(this);
  29469. this._webGLTexture = null;
  29470. this.previous = null;
  29471. this.next = null;
  29472. }
  29473. };
  29474. /**
  29475. * The source of the texture data is unknown
  29476. */
  29477. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29478. /**
  29479. * Texture data comes from an URL
  29480. */
  29481. InternalTexture.DATASOURCE_URL = 1;
  29482. /**
  29483. * Texture data is only used for temporary storage
  29484. */
  29485. InternalTexture.DATASOURCE_TEMP = 2;
  29486. /**
  29487. * Texture data comes from raw data (ArrayBuffer)
  29488. */
  29489. InternalTexture.DATASOURCE_RAW = 3;
  29490. /**
  29491. * Texture content is dynamic (video or dynamic texture)
  29492. */
  29493. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29494. /**
  29495. * Texture content is generated by rendering to it
  29496. */
  29497. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29498. /**
  29499. * Texture content is part of a multi render target process
  29500. */
  29501. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29502. /**
  29503. * Texture data comes from a cube data file
  29504. */
  29505. InternalTexture.DATASOURCE_CUBE = 7;
  29506. /**
  29507. * Texture data comes from a raw cube data
  29508. */
  29509. InternalTexture.DATASOURCE_CUBERAW = 8;
  29510. /**
  29511. * Texture data come from a prefiltered cube data file
  29512. */
  29513. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29514. /**
  29515. * Texture content is raw 3D data
  29516. */
  29517. InternalTexture.DATASOURCE_RAW3D = 10;
  29518. /**
  29519. * Texture content is a depth texture
  29520. */
  29521. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29522. return InternalTexture;
  29523. }());
  29524. BABYLON.InternalTexture = InternalTexture;
  29525. })(BABYLON || (BABYLON = {}));
  29526. //# sourceMappingURL=babylon.internalTexture.js.map
  29527. var BABYLON;
  29528. (function (BABYLON) {
  29529. var BaseTexture = /** @class */ (function () {
  29530. function BaseTexture(scene) {
  29531. this._hasAlpha = false;
  29532. this.getAlphaFromRGB = false;
  29533. this.level = 1;
  29534. this.coordinatesIndex = 0;
  29535. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29536. /**
  29537. * | Value | Type | Description |
  29538. * | ----- | ------------------ | ----------- |
  29539. * | 0 | CLAMP_ADDRESSMODE | |
  29540. * | 1 | WRAP_ADDRESSMODE | |
  29541. * | 2 | MIRROR_ADDRESSMODE | |
  29542. */
  29543. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29544. /**
  29545. * | Value | Type | Description |
  29546. * | ----- | ------------------ | ----------- |
  29547. * | 0 | CLAMP_ADDRESSMODE | |
  29548. * | 1 | WRAP_ADDRESSMODE | |
  29549. * | 2 | MIRROR_ADDRESSMODE | |
  29550. */
  29551. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29552. /**
  29553. * | Value | Type | Description |
  29554. * | ----- | ------------------ | ----------- |
  29555. * | 0 | CLAMP_ADDRESSMODE | |
  29556. * | 1 | WRAP_ADDRESSMODE | |
  29557. * | 2 | MIRROR_ADDRESSMODE | |
  29558. */
  29559. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29560. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29561. this.isCube = false;
  29562. this.is3D = false;
  29563. this.gammaSpace = true;
  29564. this.invertZ = false;
  29565. this.lodLevelInAlpha = false;
  29566. this.lodGenerationOffset = 0.0;
  29567. this.lodGenerationScale = 0.8;
  29568. this.isRenderTarget = false;
  29569. this.animations = new Array();
  29570. /**
  29571. * An event triggered when the texture is disposed.
  29572. */
  29573. this.onDisposeObservable = new BABYLON.Observable();
  29574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29575. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29576. if (this._scene) {
  29577. this._scene.textures.push(this);
  29578. }
  29579. this._uid = null;
  29580. }
  29581. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29582. get: function () {
  29583. return this._hasAlpha;
  29584. },
  29585. set: function (value) {
  29586. if (this._hasAlpha === value) {
  29587. return;
  29588. }
  29589. this._hasAlpha = value;
  29590. if (this._scene) {
  29591. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29592. }
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29598. get: function () {
  29599. return this._coordinatesMode;
  29600. },
  29601. /**
  29602. * How a texture is mapped.
  29603. *
  29604. * | Value | Type | Description |
  29605. * | ----- | ----------------------------------- | ----------- |
  29606. * | 0 | EXPLICIT_MODE | |
  29607. * | 1 | SPHERICAL_MODE | |
  29608. * | 2 | PLANAR_MODE | |
  29609. * | 3 | CUBIC_MODE | |
  29610. * | 4 | PROJECTION_MODE | |
  29611. * | 5 | SKYBOX_MODE | |
  29612. * | 6 | INVCUBIC_MODE | |
  29613. * | 7 | EQUIRECTANGULAR_MODE | |
  29614. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29615. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29616. */
  29617. set: function (value) {
  29618. if (this._coordinatesMode === value) {
  29619. return;
  29620. }
  29621. this._coordinatesMode = value;
  29622. if (this._scene) {
  29623. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29624. }
  29625. },
  29626. enumerable: true,
  29627. configurable: true
  29628. });
  29629. Object.defineProperty(BaseTexture.prototype, "uid", {
  29630. get: function () {
  29631. if (!this._uid) {
  29632. this._uid = BABYLON.Tools.RandomId();
  29633. }
  29634. return this._uid;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. BaseTexture.prototype.toString = function () {
  29640. return this.name;
  29641. };
  29642. BaseTexture.prototype.getClassName = function () {
  29643. return "BaseTexture";
  29644. };
  29645. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29646. set: function (callback) {
  29647. if (this._onDisposeObserver) {
  29648. this.onDisposeObservable.remove(this._onDisposeObserver);
  29649. }
  29650. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29656. get: function () {
  29657. return true;
  29658. },
  29659. enumerable: true,
  29660. configurable: true
  29661. });
  29662. BaseTexture.prototype.getScene = function () {
  29663. return this._scene;
  29664. };
  29665. BaseTexture.prototype.getTextureMatrix = function () {
  29666. return BABYLON.Matrix.IdentityReadOnly;
  29667. };
  29668. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29669. return BABYLON.Matrix.IdentityReadOnly;
  29670. };
  29671. BaseTexture.prototype.getInternalTexture = function () {
  29672. return this._texture;
  29673. };
  29674. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29675. return !this.isBlocking || this.isReady();
  29676. };
  29677. BaseTexture.prototype.isReady = function () {
  29678. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29679. this.delayLoad();
  29680. return false;
  29681. }
  29682. if (this._texture) {
  29683. return this._texture.isReady;
  29684. }
  29685. return false;
  29686. };
  29687. BaseTexture.prototype.getSize = function () {
  29688. if (this._texture && this._texture.width) {
  29689. return new BABYLON.Size(this._texture.width, this._texture.height);
  29690. }
  29691. if (this._texture && this._texture._size) {
  29692. return new BABYLON.Size(this._texture._size, this._texture._size);
  29693. }
  29694. return BABYLON.Size.Zero();
  29695. };
  29696. BaseTexture.prototype.getBaseSize = function () {
  29697. if (!this.isReady() || !this._texture)
  29698. return BABYLON.Size.Zero();
  29699. if (this._texture._size) {
  29700. return new BABYLON.Size(this._texture._size, this._texture._size);
  29701. }
  29702. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29703. };
  29704. BaseTexture.prototype.scale = function (ratio) {
  29705. };
  29706. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29707. get: function () {
  29708. return false;
  29709. },
  29710. enumerable: true,
  29711. configurable: true
  29712. });
  29713. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29714. if (!this._scene) {
  29715. return null;
  29716. }
  29717. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29718. for (var index = 0; index < texturesCache.length; index++) {
  29719. var texturesCacheEntry = texturesCache[index];
  29720. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29721. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29722. texturesCacheEntry.incrementReferences();
  29723. return texturesCacheEntry;
  29724. }
  29725. }
  29726. }
  29727. return null;
  29728. };
  29729. BaseTexture.prototype._rebuild = function () {
  29730. };
  29731. BaseTexture.prototype.delayLoad = function () {
  29732. };
  29733. BaseTexture.prototype.clone = function () {
  29734. return null;
  29735. };
  29736. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29737. get: function () {
  29738. if (!this._texture) {
  29739. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29740. }
  29741. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29742. },
  29743. enumerable: true,
  29744. configurable: true
  29745. });
  29746. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29747. get: function () {
  29748. if (!this._texture) {
  29749. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29750. }
  29751. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29752. },
  29753. enumerable: true,
  29754. configurable: true
  29755. });
  29756. BaseTexture.prototype.readPixels = function (faceIndex) {
  29757. if (faceIndex === void 0) { faceIndex = 0; }
  29758. if (!this._texture) {
  29759. return null;
  29760. }
  29761. var size = this.getSize();
  29762. var scene = this.getScene();
  29763. if (!scene) {
  29764. return null;
  29765. }
  29766. var engine = scene.getEngine();
  29767. if (this._texture.isCube) {
  29768. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29769. }
  29770. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29771. };
  29772. BaseTexture.prototype.releaseInternalTexture = function () {
  29773. if (this._texture) {
  29774. this._texture.dispose();
  29775. this._texture = null;
  29776. }
  29777. };
  29778. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29779. get: function () {
  29780. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29781. return null;
  29782. }
  29783. if (!this._texture._sphericalPolynomial) {
  29784. this._texture._sphericalPolynomial =
  29785. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29786. }
  29787. return this._texture._sphericalPolynomial;
  29788. },
  29789. set: function (value) {
  29790. if (this._texture) {
  29791. this._texture._sphericalPolynomial = value;
  29792. }
  29793. },
  29794. enumerable: true,
  29795. configurable: true
  29796. });
  29797. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29798. get: function () {
  29799. if (this._texture) {
  29800. return this._texture._lodTextureHigh;
  29801. }
  29802. return null;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29808. get: function () {
  29809. if (this._texture) {
  29810. return this._texture._lodTextureMid;
  29811. }
  29812. return null;
  29813. },
  29814. enumerable: true,
  29815. configurable: true
  29816. });
  29817. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29818. get: function () {
  29819. if (this._texture) {
  29820. return this._texture._lodTextureLow;
  29821. }
  29822. return null;
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. BaseTexture.prototype.dispose = function () {
  29828. if (!this._scene) {
  29829. return;
  29830. }
  29831. // Animations
  29832. this._scene.stopAnimation(this);
  29833. // Remove from scene
  29834. this._scene._removePendingData(this);
  29835. var index = this._scene.textures.indexOf(this);
  29836. if (index >= 0) {
  29837. this._scene.textures.splice(index, 1);
  29838. }
  29839. if (this._texture === undefined) {
  29840. return;
  29841. }
  29842. // Release
  29843. this.releaseInternalTexture();
  29844. // Callback
  29845. this.onDisposeObservable.notifyObservers(this);
  29846. this.onDisposeObservable.clear();
  29847. };
  29848. BaseTexture.prototype.serialize = function () {
  29849. if (!this.name) {
  29850. return null;
  29851. }
  29852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29853. // Animations
  29854. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29855. return serializationObject;
  29856. };
  29857. BaseTexture.WhenAllReady = function (textures, callback) {
  29858. var numRemaining = textures.length;
  29859. if (numRemaining === 0) {
  29860. callback();
  29861. return;
  29862. }
  29863. var _loop_1 = function () {
  29864. texture = textures[i];
  29865. if (texture.isReady()) {
  29866. if (--numRemaining === 0) {
  29867. callback();
  29868. }
  29869. }
  29870. else {
  29871. onLoadObservable = texture.onLoadObservable;
  29872. var onLoadCallback_1 = function () {
  29873. onLoadObservable.removeCallback(onLoadCallback_1);
  29874. if (--numRemaining === 0) {
  29875. callback();
  29876. }
  29877. };
  29878. onLoadObservable.add(onLoadCallback_1);
  29879. }
  29880. };
  29881. var texture, onLoadObservable;
  29882. for (var i = 0; i < textures.length; i++) {
  29883. _loop_1();
  29884. }
  29885. };
  29886. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29887. __decorate([
  29888. BABYLON.serialize()
  29889. ], BaseTexture.prototype, "name", void 0);
  29890. __decorate([
  29891. BABYLON.serialize("hasAlpha")
  29892. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29893. __decorate([
  29894. BABYLON.serialize()
  29895. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29896. __decorate([
  29897. BABYLON.serialize()
  29898. ], BaseTexture.prototype, "level", void 0);
  29899. __decorate([
  29900. BABYLON.serialize()
  29901. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29902. __decorate([
  29903. BABYLON.serialize("coordinatesMode")
  29904. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29905. __decorate([
  29906. BABYLON.serialize()
  29907. ], BaseTexture.prototype, "wrapU", void 0);
  29908. __decorate([
  29909. BABYLON.serialize()
  29910. ], BaseTexture.prototype, "wrapV", void 0);
  29911. __decorate([
  29912. BABYLON.serialize()
  29913. ], BaseTexture.prototype, "wrapR", void 0);
  29914. __decorate([
  29915. BABYLON.serialize()
  29916. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29917. __decorate([
  29918. BABYLON.serialize()
  29919. ], BaseTexture.prototype, "isCube", void 0);
  29920. __decorate([
  29921. BABYLON.serialize()
  29922. ], BaseTexture.prototype, "is3D", void 0);
  29923. __decorate([
  29924. BABYLON.serialize()
  29925. ], BaseTexture.prototype, "gammaSpace", void 0);
  29926. __decorate([
  29927. BABYLON.serialize()
  29928. ], BaseTexture.prototype, "invertZ", void 0);
  29929. __decorate([
  29930. BABYLON.serialize()
  29931. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29932. __decorate([
  29933. BABYLON.serialize()
  29934. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29935. __decorate([
  29936. BABYLON.serialize()
  29937. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29938. __decorate([
  29939. BABYLON.serialize()
  29940. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29941. return BaseTexture;
  29942. }());
  29943. BABYLON.BaseTexture = BaseTexture;
  29944. })(BABYLON || (BABYLON = {}));
  29945. //# sourceMappingURL=babylon.baseTexture.js.map
  29946. var BABYLON;
  29947. (function (BABYLON) {
  29948. var Texture = /** @class */ (function (_super) {
  29949. __extends(Texture, _super);
  29950. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29951. if (noMipmap === void 0) { noMipmap = false; }
  29952. if (invertY === void 0) { invertY = true; }
  29953. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29954. if (onLoad === void 0) { onLoad = null; }
  29955. if (onError === void 0) { onError = null; }
  29956. if (buffer === void 0) { buffer = null; }
  29957. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29958. var _this = _super.call(this, scene) || this;
  29959. _this.uOffset = 0;
  29960. _this.vOffset = 0;
  29961. _this.uScale = 1.0;
  29962. _this.vScale = 1.0;
  29963. _this.uAng = 0;
  29964. _this.vAng = 0;
  29965. _this.wAng = 0;
  29966. _this._isBlocking = true;
  29967. _this.name = url || "";
  29968. _this.url = url;
  29969. _this._noMipmap = noMipmap;
  29970. _this._invertY = invertY;
  29971. _this._samplingMode = samplingMode;
  29972. _this._buffer = buffer;
  29973. _this._deleteBuffer = deleteBuffer;
  29974. if (format) {
  29975. _this._format = format;
  29976. }
  29977. scene = _this.getScene();
  29978. if (!scene) {
  29979. return _this;
  29980. }
  29981. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29982. var load = function () {
  29983. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29984. _this.onLoadObservable.notifyObservers(_this);
  29985. }
  29986. if (onLoad) {
  29987. onLoad();
  29988. }
  29989. if (!_this.isBlocking && scene) {
  29990. scene.resetCachedMaterial();
  29991. }
  29992. };
  29993. if (!_this.url) {
  29994. _this._delayedOnLoad = load;
  29995. _this._delayedOnError = onError;
  29996. return _this;
  29997. }
  29998. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29999. if (!_this._texture) {
  30000. if (!scene.useDelayedTextureLoading) {
  30001. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30002. if (deleteBuffer) {
  30003. delete _this._buffer;
  30004. }
  30005. }
  30006. else {
  30007. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30008. _this._delayedOnLoad = load;
  30009. _this._delayedOnError = onError;
  30010. }
  30011. }
  30012. else {
  30013. if (_this._texture.isReady) {
  30014. BABYLON.Tools.SetImmediate(function () { return load(); });
  30015. }
  30016. else {
  30017. _this._texture.onLoadedObservable.add(load);
  30018. }
  30019. }
  30020. return _this;
  30021. }
  30022. Object.defineProperty(Texture.prototype, "noMipmap", {
  30023. get: function () {
  30024. return this._noMipmap;
  30025. },
  30026. enumerable: true,
  30027. configurable: true
  30028. });
  30029. Object.defineProperty(Texture.prototype, "isBlocking", {
  30030. get: function () {
  30031. return this._isBlocking;
  30032. },
  30033. set: function (value) {
  30034. this._isBlocking = value;
  30035. },
  30036. enumerable: true,
  30037. configurable: true
  30038. });
  30039. Object.defineProperty(Texture.prototype, "samplingMode", {
  30040. get: function () {
  30041. return this._samplingMode;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. Texture.prototype.updateURL = function (url) {
  30047. this.url = url;
  30048. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30049. this.delayLoad();
  30050. };
  30051. Texture.prototype.delayLoad = function () {
  30052. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30053. return;
  30054. }
  30055. var scene = this.getScene();
  30056. if (!scene) {
  30057. return;
  30058. }
  30059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30060. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30061. if (!this._texture) {
  30062. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30063. if (this._deleteBuffer) {
  30064. delete this._buffer;
  30065. }
  30066. }
  30067. else {
  30068. if (this._delayedOnLoad) {
  30069. if (this._texture.isReady) {
  30070. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30071. }
  30072. else {
  30073. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30074. }
  30075. }
  30076. }
  30077. this._delayedOnLoad = null;
  30078. this._delayedOnError = null;
  30079. };
  30080. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30081. if (!this._texture) {
  30082. return;
  30083. }
  30084. var scene = this.getScene();
  30085. if (!scene) {
  30086. return;
  30087. }
  30088. this._samplingMode = samplingMode;
  30089. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30090. };
  30091. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30092. x *= this.uScale;
  30093. y *= this.vScale;
  30094. x -= 0.5 * this.uScale;
  30095. y -= 0.5 * this.vScale;
  30096. z -= 0.5;
  30097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30098. t.x += 0.5 * this.uScale + this.uOffset;
  30099. t.y += 0.5 * this.vScale + this.vOffset;
  30100. t.z += 0.5;
  30101. };
  30102. Texture.prototype.getTextureMatrix = function () {
  30103. var _this = this;
  30104. if (this.uOffset === this._cachedUOffset &&
  30105. this.vOffset === this._cachedVOffset &&
  30106. this.uScale === this._cachedUScale &&
  30107. this.vScale === this._cachedVScale &&
  30108. this.uAng === this._cachedUAng &&
  30109. this.vAng === this._cachedVAng &&
  30110. this.wAng === this._cachedWAng) {
  30111. return this._cachedTextureMatrix;
  30112. }
  30113. this._cachedUOffset = this.uOffset;
  30114. this._cachedVOffset = this.vOffset;
  30115. this._cachedUScale = this.uScale;
  30116. this._cachedVScale = this.vScale;
  30117. this._cachedUAng = this.uAng;
  30118. this._cachedVAng = this.vAng;
  30119. this._cachedWAng = this.wAng;
  30120. if (!this._cachedTextureMatrix) {
  30121. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30122. this._rowGenerationMatrix = new BABYLON.Matrix();
  30123. this._t0 = BABYLON.Vector3.Zero();
  30124. this._t1 = BABYLON.Vector3.Zero();
  30125. this._t2 = BABYLON.Vector3.Zero();
  30126. }
  30127. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30128. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30129. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30130. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30131. this._t1.subtractInPlace(this._t0);
  30132. this._t2.subtractInPlace(this._t0);
  30133. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30134. this._cachedTextureMatrix.m[0] = this._t1.x;
  30135. this._cachedTextureMatrix.m[1] = this._t1.y;
  30136. this._cachedTextureMatrix.m[2] = this._t1.z;
  30137. this._cachedTextureMatrix.m[4] = this._t2.x;
  30138. this._cachedTextureMatrix.m[5] = this._t2.y;
  30139. this._cachedTextureMatrix.m[6] = this._t2.z;
  30140. this._cachedTextureMatrix.m[8] = this._t0.x;
  30141. this._cachedTextureMatrix.m[9] = this._t0.y;
  30142. this._cachedTextureMatrix.m[10] = this._t0.z;
  30143. var scene = this.getScene();
  30144. if (!scene) {
  30145. return this._cachedTextureMatrix;
  30146. }
  30147. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30148. return mat.hasTexture(_this);
  30149. });
  30150. return this._cachedTextureMatrix;
  30151. };
  30152. Texture.prototype.getReflectionTextureMatrix = function () {
  30153. var _this = this;
  30154. var scene = this.getScene();
  30155. if (!scene) {
  30156. return this._cachedTextureMatrix;
  30157. }
  30158. if (this.uOffset === this._cachedUOffset &&
  30159. this.vOffset === this._cachedVOffset &&
  30160. this.uScale === this._cachedUScale &&
  30161. this.vScale === this._cachedVScale &&
  30162. this.coordinatesMode === this._cachedCoordinatesMode) {
  30163. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30164. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30165. return this._cachedTextureMatrix;
  30166. }
  30167. }
  30168. else {
  30169. return this._cachedTextureMatrix;
  30170. }
  30171. }
  30172. if (!this._cachedTextureMatrix) {
  30173. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30174. }
  30175. if (!this._projectionModeMatrix) {
  30176. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30177. }
  30178. this._cachedUOffset = this.uOffset;
  30179. this._cachedVOffset = this.vOffset;
  30180. this._cachedUScale = this.uScale;
  30181. this._cachedVScale = this.vScale;
  30182. this._cachedCoordinatesMode = this.coordinatesMode;
  30183. switch (this.coordinatesMode) {
  30184. case Texture.PLANAR_MODE:
  30185. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30186. this._cachedTextureMatrix[0] = this.uScale;
  30187. this._cachedTextureMatrix[5] = this.vScale;
  30188. this._cachedTextureMatrix[12] = this.uOffset;
  30189. this._cachedTextureMatrix[13] = this.vOffset;
  30190. break;
  30191. case Texture.PROJECTION_MODE:
  30192. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30193. this._projectionModeMatrix.m[0] = 0.5;
  30194. this._projectionModeMatrix.m[5] = -0.5;
  30195. this._projectionModeMatrix.m[10] = 0.0;
  30196. this._projectionModeMatrix.m[12] = 0.5;
  30197. this._projectionModeMatrix.m[13] = 0.5;
  30198. this._projectionModeMatrix.m[14] = 1.0;
  30199. this._projectionModeMatrix.m[15] = 1.0;
  30200. var projectionMatrix = scene.getProjectionMatrix();
  30201. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30202. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30203. break;
  30204. default:
  30205. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30206. break;
  30207. }
  30208. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30209. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30210. });
  30211. return this._cachedTextureMatrix;
  30212. };
  30213. Texture.prototype.clone = function () {
  30214. var _this = this;
  30215. return BABYLON.SerializationHelper.Clone(function () {
  30216. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30217. }, this);
  30218. };
  30219. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30220. get: function () {
  30221. if (!this._onLoadObservable) {
  30222. this._onLoadObservable = new BABYLON.Observable();
  30223. }
  30224. return this._onLoadObservable;
  30225. },
  30226. enumerable: true,
  30227. configurable: true
  30228. });
  30229. Texture.prototype.serialize = function () {
  30230. var serializationObject = _super.prototype.serialize.call(this);
  30231. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30232. serializationObject.base64String = this._buffer;
  30233. serializationObject.name = serializationObject.name.replace("data:", "");
  30234. }
  30235. serializationObject.invertY = this._invertY;
  30236. serializationObject.samplingMode = this.samplingMode;
  30237. return serializationObject;
  30238. };
  30239. Texture.prototype.getClassName = function () {
  30240. return "Texture";
  30241. };
  30242. Texture.prototype.dispose = function () {
  30243. _super.prototype.dispose.call(this);
  30244. if (this.onLoadObservable) {
  30245. this.onLoadObservable.clear();
  30246. this._onLoadObservable = null;
  30247. }
  30248. this._delayedOnLoad = null;
  30249. this._delayedOnError = null;
  30250. };
  30251. // Statics
  30252. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30253. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30254. if (onLoad === void 0) { onLoad = null; }
  30255. if (onError === void 0) { onError = null; }
  30256. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30257. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30258. };
  30259. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30260. if (parsedTexture.customType) {
  30261. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30262. // Update Sampling Mode
  30263. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30264. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30265. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30266. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30267. }
  30268. }
  30269. return parsedCustomTexture;
  30270. }
  30271. if (parsedTexture.isCube) {
  30272. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30273. }
  30274. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30275. return null;
  30276. }
  30277. var texture = BABYLON.SerializationHelper.Parse(function () {
  30278. var generateMipMaps = true;
  30279. if (parsedTexture.noMipmap) {
  30280. generateMipMaps = false;
  30281. }
  30282. if (parsedTexture.mirrorPlane) {
  30283. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30284. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30285. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30286. return mirrorTexture;
  30287. }
  30288. else if (parsedTexture.isRenderTarget) {
  30289. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30290. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30291. return renderTargetTexture;
  30292. }
  30293. else {
  30294. var texture;
  30295. if (parsedTexture.base64String) {
  30296. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30297. }
  30298. else {
  30299. var url = rootUrl + parsedTexture.name;
  30300. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30301. url = parsedTexture.url;
  30302. }
  30303. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30304. }
  30305. return texture;
  30306. }
  30307. }, parsedTexture, scene);
  30308. // Update Sampling Mode
  30309. if (parsedTexture.samplingMode) {
  30310. var sampling = parsedTexture.samplingMode;
  30311. if (texture._samplingMode !== sampling) {
  30312. texture.updateSamplingMode(sampling);
  30313. }
  30314. }
  30315. // Animations
  30316. if (parsedTexture.animations) {
  30317. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30318. var parsedAnimation = parsedTexture.animations[animationIndex];
  30319. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30320. }
  30321. }
  30322. return texture;
  30323. };
  30324. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30325. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30326. if (noMipmap === void 0) { noMipmap = false; }
  30327. if (invertY === void 0) { invertY = true; }
  30328. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30329. if (onLoad === void 0) { onLoad = null; }
  30330. if (onError === void 0) { onError = null; }
  30331. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30332. if (name.substr(0, 5) !== "data:") {
  30333. name = "data:" + name;
  30334. }
  30335. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30336. };
  30337. // Constants
  30338. Texture.NEAREST_SAMPLINGMODE = 1;
  30339. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30340. Texture.BILINEAR_SAMPLINGMODE = 2;
  30341. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30342. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30343. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30344. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30345. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30346. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30347. Texture.NEAREST_LINEAR = 7;
  30348. Texture.NEAREST_NEAREST = 8;
  30349. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30350. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30351. Texture.LINEAR_LINEAR = 11;
  30352. Texture.LINEAR_NEAREST = 12;
  30353. Texture.EXPLICIT_MODE = 0;
  30354. Texture.SPHERICAL_MODE = 1;
  30355. Texture.PLANAR_MODE = 2;
  30356. Texture.CUBIC_MODE = 3;
  30357. Texture.PROJECTION_MODE = 4;
  30358. Texture.SKYBOX_MODE = 5;
  30359. Texture.INVCUBIC_MODE = 6;
  30360. Texture.EQUIRECTANGULAR_MODE = 7;
  30361. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30362. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30363. Texture.CLAMP_ADDRESSMODE = 0;
  30364. Texture.WRAP_ADDRESSMODE = 1;
  30365. Texture.MIRROR_ADDRESSMODE = 2;
  30366. /**
  30367. * 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
  30368. */
  30369. Texture.UseSerializedUrlIfAny = false;
  30370. __decorate([
  30371. BABYLON.serialize()
  30372. ], Texture.prototype, "url", void 0);
  30373. __decorate([
  30374. BABYLON.serialize()
  30375. ], Texture.prototype, "uOffset", void 0);
  30376. __decorate([
  30377. BABYLON.serialize()
  30378. ], Texture.prototype, "vOffset", void 0);
  30379. __decorate([
  30380. BABYLON.serialize()
  30381. ], Texture.prototype, "uScale", void 0);
  30382. __decorate([
  30383. BABYLON.serialize()
  30384. ], Texture.prototype, "vScale", void 0);
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], Texture.prototype, "uAng", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], Texture.prototype, "vAng", void 0);
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], Texture.prototype, "wAng", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], Texture.prototype, "isBlocking", null);
  30397. return Texture;
  30398. }(BABYLON.BaseTexture));
  30399. BABYLON.Texture = Texture;
  30400. })(BABYLON || (BABYLON = {}));
  30401. //# sourceMappingURL=babylon.texture.js.map
  30402. var BABYLON;
  30403. (function (BABYLON) {
  30404. var _InstancesBatch = /** @class */ (function () {
  30405. function _InstancesBatch() {
  30406. this.mustReturn = false;
  30407. this.visibleInstances = new Array();
  30408. this.renderSelf = new Array();
  30409. }
  30410. return _InstancesBatch;
  30411. }());
  30412. BABYLON._InstancesBatch = _InstancesBatch;
  30413. var Mesh = /** @class */ (function (_super) {
  30414. __extends(Mesh, _super);
  30415. /**
  30416. * @constructor
  30417. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30418. * @param {Scene} scene The scene to add this mesh to.
  30419. * @param {Node} parent The parent of this mesh, if it has one
  30420. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30421. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30422. * When false, achieved by calling a clone(), also passing False.
  30423. * This will make creation of children, recursive.
  30424. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30425. */
  30426. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30427. if (scene === void 0) { scene = null; }
  30428. if (parent === void 0) { parent = null; }
  30429. if (source === void 0) { source = null; }
  30430. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30431. var _this = _super.call(this, name, scene) || this;
  30432. // Events
  30433. /**
  30434. * An event triggered before rendering the mesh
  30435. */
  30436. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30437. /**
  30438. * An event triggered after rendering the mesh
  30439. */
  30440. _this.onAfterRenderObservable = new BABYLON.Observable();
  30441. /**
  30442. * An event triggered before drawing the mesh
  30443. */
  30444. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30445. // Members
  30446. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30447. _this.instances = new Array();
  30448. _this._LODLevels = new Array();
  30449. _this._visibleInstances = {};
  30450. _this._renderIdForInstances = new Array();
  30451. _this._batchCache = new _InstancesBatch();
  30452. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30453. // Use by builder only to know what orientation were the mesh build in.
  30454. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30455. _this.overrideMaterialSideOrientation = null;
  30456. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30457. // Will be used to save a source mesh reference, If any
  30458. _this._source = null;
  30459. scene = _this.getScene();
  30460. if (source) {
  30461. // Source mesh
  30462. _this._source = source;
  30463. // Geometry
  30464. if (source._geometry) {
  30465. source._geometry.applyToMesh(_this);
  30466. }
  30467. // Deep copy
  30468. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30469. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30470. // Metadata
  30471. if (source.metadata && source.metadata.clone) {
  30472. _this.metadata = source.metadata.clone();
  30473. }
  30474. else {
  30475. _this.metadata = source.metadata;
  30476. }
  30477. // Tags
  30478. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30479. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30480. }
  30481. // Parent
  30482. _this.parent = source.parent;
  30483. // Pivot
  30484. _this.setPivotMatrix(source.getPivotMatrix());
  30485. _this.id = name + "." + source.id;
  30486. // Material
  30487. _this.material = source.material;
  30488. var index;
  30489. if (!doNotCloneChildren) {
  30490. // Children
  30491. var directDescendants = source.getDescendants(true);
  30492. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30493. var child = directDescendants[index_1];
  30494. if (child.clone) {
  30495. child.clone(name + "." + child.name, _this);
  30496. }
  30497. }
  30498. }
  30499. // Physics clone
  30500. var physicsEngine = _this.getScene().getPhysicsEngine();
  30501. if (clonePhysicsImpostor && physicsEngine) {
  30502. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30503. if (impostor) {
  30504. _this.physicsImpostor = impostor.clone(_this);
  30505. }
  30506. }
  30507. // Particles
  30508. for (index = 0; index < scene.particleSystems.length; index++) {
  30509. var system = scene.particleSystems[index];
  30510. if (system.emitter === source) {
  30511. system.clone(system.name, _this);
  30512. }
  30513. }
  30514. _this.computeWorldMatrix(true);
  30515. }
  30516. // Parent
  30517. if (parent !== null) {
  30518. _this.parent = parent;
  30519. }
  30520. return _this;
  30521. }
  30522. Object.defineProperty(Mesh, "FRONTSIDE", {
  30523. /**
  30524. * Mesh side orientation : usually the external or front surface
  30525. */
  30526. get: function () {
  30527. return Mesh._FRONTSIDE;
  30528. },
  30529. enumerable: true,
  30530. configurable: true
  30531. });
  30532. Object.defineProperty(Mesh, "BACKSIDE", {
  30533. /**
  30534. * Mesh side orientation : usually the internal or back surface
  30535. */
  30536. get: function () {
  30537. return Mesh._BACKSIDE;
  30538. },
  30539. enumerable: true,
  30540. configurable: true
  30541. });
  30542. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30543. /**
  30544. * Mesh side orientation : both internal and external or front and back surfaces
  30545. */
  30546. get: function () {
  30547. return Mesh._DOUBLESIDE;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30553. /**
  30554. * Mesh side orientation : by default, `FRONTSIDE`
  30555. */
  30556. get: function () {
  30557. return Mesh._DEFAULTSIDE;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(Mesh, "NO_CAP", {
  30563. /**
  30564. * Mesh cap setting : no cap
  30565. */
  30566. get: function () {
  30567. return Mesh._NO_CAP;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. Object.defineProperty(Mesh, "CAP_START", {
  30573. /**
  30574. * Mesh cap setting : one cap at the beginning of the mesh
  30575. */
  30576. get: function () {
  30577. return Mesh._CAP_START;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(Mesh, "CAP_END", {
  30583. /**
  30584. * Mesh cap setting : one cap at the end of the mesh
  30585. */
  30586. get: function () {
  30587. return Mesh._CAP_END;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. Object.defineProperty(Mesh, "CAP_ALL", {
  30593. /**
  30594. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30595. */
  30596. get: function () {
  30597. return Mesh._CAP_ALL;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30603. set: function (callback) {
  30604. if (this._onBeforeDrawObserver) {
  30605. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30606. }
  30607. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30613. get: function () {
  30614. return this._morphTargetManager;
  30615. },
  30616. set: function (value) {
  30617. if (this._morphTargetManager === value) {
  30618. return;
  30619. }
  30620. this._morphTargetManager = value;
  30621. this._syncGeometryWithMorphTargetManager();
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(Mesh.prototype, "source", {
  30627. get: function () {
  30628. return this._source;
  30629. },
  30630. enumerable: true,
  30631. configurable: true
  30632. });
  30633. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30634. get: function () {
  30635. return this._unIndexed;
  30636. },
  30637. set: function (value) {
  30638. if (this._unIndexed !== value) {
  30639. this._unIndexed = value;
  30640. this._markSubMeshesAsAttributesDirty();
  30641. }
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. // Methods
  30647. /**
  30648. * Returns the string "Mesh".
  30649. */
  30650. Mesh.prototype.getClassName = function () {
  30651. return "Mesh";
  30652. };
  30653. /**
  30654. * Returns a string.
  30655. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30656. */
  30657. Mesh.prototype.toString = function (fullDetails) {
  30658. var ret = _super.prototype.toString.call(this, fullDetails);
  30659. ret += ", n vertices: " + this.getTotalVertices();
  30660. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30661. if (this.animations) {
  30662. for (var i = 0; i < this.animations.length; i++) {
  30663. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30664. }
  30665. }
  30666. if (fullDetails) {
  30667. if (this._geometry) {
  30668. var ib = this.getIndices();
  30669. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30670. if (vb && ib) {
  30671. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30672. }
  30673. }
  30674. else {
  30675. ret += ", flat shading: UNKNOWN";
  30676. }
  30677. }
  30678. return ret;
  30679. };
  30680. Mesh.prototype._unBindEffect = function () {
  30681. _super.prototype._unBindEffect.call(this);
  30682. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30683. var instance = _a[_i];
  30684. instance._unBindEffect();
  30685. }
  30686. };
  30687. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30688. /**
  30689. * True if the mesh has some Levels Of Details (LOD).
  30690. * Returns a boolean.
  30691. */
  30692. get: function () {
  30693. return this._LODLevels.length > 0;
  30694. },
  30695. enumerable: true,
  30696. configurable: true
  30697. });
  30698. /**
  30699. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30700. * @returns an array of {BABYLON.MeshLODLevel}
  30701. */
  30702. Mesh.prototype.getLODLevels = function () {
  30703. return this._LODLevels;
  30704. };
  30705. Mesh.prototype._sortLODLevels = function () {
  30706. this._LODLevels.sort(function (a, b) {
  30707. if (a.distance < b.distance) {
  30708. return 1;
  30709. }
  30710. if (a.distance > b.distance) {
  30711. return -1;
  30712. }
  30713. return 0;
  30714. });
  30715. };
  30716. /**
  30717. * Add a mesh as LOD level triggered at the given distance.
  30718. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30719. * @param {number} distance The distance from the center of the object to show this level
  30720. * @param {Mesh} mesh The mesh to be added as LOD level
  30721. * @return {Mesh} This mesh (for chaining)
  30722. */
  30723. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30724. if (mesh && mesh._masterMesh) {
  30725. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30726. return this;
  30727. }
  30728. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30729. this._LODLevels.push(level);
  30730. if (mesh) {
  30731. mesh._masterMesh = this;
  30732. }
  30733. this._sortLODLevels();
  30734. return this;
  30735. };
  30736. /**
  30737. * Returns the LOD level mesh at the passed distance or null if not found.
  30738. * It is related to the method `addLODLevel(distance, mesh)`.
  30739. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30740. * Returns an object Mesh or `null`.
  30741. */
  30742. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30743. for (var index = 0; index < this._LODLevels.length; index++) {
  30744. var level = this._LODLevels[index];
  30745. if (level.distance === distance) {
  30746. return level.mesh;
  30747. }
  30748. }
  30749. return null;
  30750. };
  30751. /**
  30752. * Remove a mesh from the LOD array
  30753. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30754. * @param {Mesh} mesh The mesh to be removed.
  30755. * @return {Mesh} This mesh (for chaining)
  30756. */
  30757. Mesh.prototype.removeLODLevel = function (mesh) {
  30758. for (var index = 0; index < this._LODLevels.length; index++) {
  30759. if (this._LODLevels[index].mesh === mesh) {
  30760. this._LODLevels.splice(index, 1);
  30761. if (mesh) {
  30762. mesh._masterMesh = null;
  30763. }
  30764. }
  30765. }
  30766. this._sortLODLevels();
  30767. return this;
  30768. };
  30769. /**
  30770. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30771. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30772. */
  30773. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30774. if (!this._LODLevels || this._LODLevels.length === 0) {
  30775. return this;
  30776. }
  30777. var bSphere;
  30778. if (boundingSphere) {
  30779. bSphere = boundingSphere;
  30780. }
  30781. else {
  30782. var boundingInfo = this.getBoundingInfo();
  30783. bSphere = boundingInfo.boundingSphere;
  30784. }
  30785. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30786. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30787. if (this.onLODLevelSelection) {
  30788. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30789. }
  30790. return this;
  30791. }
  30792. for (var index = 0; index < this._LODLevels.length; index++) {
  30793. var level = this._LODLevels[index];
  30794. if (level.distance < distanceToCamera) {
  30795. if (level.mesh) {
  30796. level.mesh._preActivate();
  30797. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30798. }
  30799. if (this.onLODLevelSelection) {
  30800. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30801. }
  30802. return level.mesh;
  30803. }
  30804. }
  30805. if (this.onLODLevelSelection) {
  30806. this.onLODLevelSelection(distanceToCamera, this, this);
  30807. }
  30808. return this;
  30809. };
  30810. Object.defineProperty(Mesh.prototype, "geometry", {
  30811. /**
  30812. * Returns the mesh internal Geometry object.
  30813. */
  30814. get: function () {
  30815. return this._geometry;
  30816. },
  30817. enumerable: true,
  30818. configurable: true
  30819. });
  30820. /**
  30821. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30822. */
  30823. Mesh.prototype.getTotalVertices = function () {
  30824. if (this._geometry === null || this._geometry === undefined) {
  30825. return 0;
  30826. }
  30827. return this._geometry.getTotalVertices();
  30828. };
  30829. /**
  30830. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30831. * 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.
  30832. * You can force the copy with forceCopy === true
  30833. * Returns null if the mesh has no geometry or no vertex buffer.
  30834. * Possible `kind` values :
  30835. * - BABYLON.VertexBuffer.PositionKind
  30836. * - BABYLON.VertexBuffer.UVKind
  30837. * - BABYLON.VertexBuffer.UV2Kind
  30838. * - BABYLON.VertexBuffer.UV3Kind
  30839. * - BABYLON.VertexBuffer.UV4Kind
  30840. * - BABYLON.VertexBuffer.UV5Kind
  30841. * - BABYLON.VertexBuffer.UV6Kind
  30842. * - BABYLON.VertexBuffer.ColorKind
  30843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30847. */
  30848. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30849. if (!this._geometry) {
  30850. return null;
  30851. }
  30852. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30853. };
  30854. /**
  30855. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30856. * Returns `null` if the mesh has no geometry.
  30857. * Possible `kind` values :
  30858. * - BABYLON.VertexBuffer.PositionKind
  30859. * - BABYLON.VertexBuffer.UVKind
  30860. * - BABYLON.VertexBuffer.UV2Kind
  30861. * - BABYLON.VertexBuffer.UV3Kind
  30862. * - BABYLON.VertexBuffer.UV4Kind
  30863. * - BABYLON.VertexBuffer.UV5Kind
  30864. * - BABYLON.VertexBuffer.UV6Kind
  30865. * - BABYLON.VertexBuffer.ColorKind
  30866. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30867. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30868. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30869. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30870. */
  30871. Mesh.prototype.getVertexBuffer = function (kind) {
  30872. if (!this._geometry) {
  30873. return null;
  30874. }
  30875. return this._geometry.getVertexBuffer(kind);
  30876. };
  30877. /**
  30878. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30879. * Possible `kind` values :
  30880. * - BABYLON.VertexBuffer.PositionKind
  30881. * - BABYLON.VertexBuffer.UVKind
  30882. * - BABYLON.VertexBuffer.UV2Kind
  30883. * - BABYLON.VertexBuffer.UV3Kind
  30884. * - BABYLON.VertexBuffer.UV4Kind
  30885. * - BABYLON.VertexBuffer.UV5Kind
  30886. * - BABYLON.VertexBuffer.UV6Kind
  30887. * - BABYLON.VertexBuffer.ColorKind
  30888. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30889. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30890. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30891. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30892. */
  30893. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30894. if (!this._geometry) {
  30895. if (this._delayInfo) {
  30896. return this._delayInfo.indexOf(kind) !== -1;
  30897. }
  30898. return false;
  30899. }
  30900. return this._geometry.isVerticesDataPresent(kind);
  30901. };
  30902. /**
  30903. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30904. * Possible `kind` values :
  30905. * - BABYLON.VertexBuffer.PositionKind
  30906. * - BABYLON.VertexBuffer.UVKind
  30907. * - BABYLON.VertexBuffer.UV2Kind
  30908. * - BABYLON.VertexBuffer.UV3Kind
  30909. * - BABYLON.VertexBuffer.UV4Kind
  30910. * - BABYLON.VertexBuffer.UV5Kind
  30911. * - BABYLON.VertexBuffer.UV6Kind
  30912. * - BABYLON.VertexBuffer.ColorKind
  30913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30917. */
  30918. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30919. if (!this._geometry) {
  30920. if (this._delayInfo) {
  30921. return this._delayInfo.indexOf(kind) !== -1;
  30922. }
  30923. return false;
  30924. }
  30925. return this._geometry.isVertexBufferUpdatable(kind);
  30926. };
  30927. /**
  30928. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30929. * Possible `kind` values :
  30930. * - BABYLON.VertexBuffer.PositionKind
  30931. * - BABYLON.VertexBuffer.UVKind
  30932. * - BABYLON.VertexBuffer.UV2Kind
  30933. * - BABYLON.VertexBuffer.UV3Kind
  30934. * - BABYLON.VertexBuffer.UV4Kind
  30935. * - BABYLON.VertexBuffer.UV5Kind
  30936. * - BABYLON.VertexBuffer.UV6Kind
  30937. * - BABYLON.VertexBuffer.ColorKind
  30938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30942. */
  30943. Mesh.prototype.getVerticesDataKinds = function () {
  30944. if (!this._geometry) {
  30945. var result = new Array();
  30946. if (this._delayInfo) {
  30947. this._delayInfo.forEach(function (kind, index, array) {
  30948. result.push(kind);
  30949. });
  30950. }
  30951. return result;
  30952. }
  30953. return this._geometry.getVerticesDataKinds();
  30954. };
  30955. /**
  30956. * Returns a positive integer : the total number of indices in this mesh geometry.
  30957. * Returns zero if the mesh has no geometry.
  30958. */
  30959. Mesh.prototype.getTotalIndices = function () {
  30960. if (!this._geometry) {
  30961. return 0;
  30962. }
  30963. return this._geometry.getTotalIndices();
  30964. };
  30965. /**
  30966. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30967. * 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.
  30968. * Returns an empty array if the mesh has no geometry.
  30969. */
  30970. Mesh.prototype.getIndices = function (copyWhenShared) {
  30971. if (!this._geometry) {
  30972. return [];
  30973. }
  30974. return this._geometry.getIndices(copyWhenShared);
  30975. };
  30976. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30977. get: function () {
  30978. return this._masterMesh !== null && this._masterMesh !== undefined;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. /**
  30984. * Determine if the current mesh is ready to be rendered
  30985. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30986. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30987. * @returns true if all associated assets are ready (material, textures, shaders)
  30988. */
  30989. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30990. if (completeCheck === void 0) { completeCheck = false; }
  30991. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30992. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30993. return false;
  30994. }
  30995. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30996. return false;
  30997. }
  30998. if (!this.subMeshes || this.subMeshes.length === 0) {
  30999. return true;
  31000. }
  31001. if (!completeCheck) {
  31002. return true;
  31003. }
  31004. var engine = this.getEngine();
  31005. var scene = this.getScene();
  31006. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31007. this.computeWorldMatrix();
  31008. var mat = this.material || scene.defaultMaterial;
  31009. if (mat) {
  31010. if (mat.storeEffectOnSubMeshes) {
  31011. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31012. var subMesh = _a[_i];
  31013. var effectiveMaterial = subMesh.getMaterial();
  31014. if (effectiveMaterial) {
  31015. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31016. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31017. return false;
  31018. }
  31019. }
  31020. else {
  31021. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31022. return false;
  31023. }
  31024. }
  31025. }
  31026. }
  31027. }
  31028. else {
  31029. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31030. return false;
  31031. }
  31032. }
  31033. }
  31034. // Shadows
  31035. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31036. var light = _c[_b];
  31037. var generator = light.getShadowGenerator();
  31038. if (generator) {
  31039. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31040. var subMesh = _e[_d];
  31041. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31042. return false;
  31043. }
  31044. }
  31045. }
  31046. }
  31047. // LOD
  31048. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31049. var lod = _g[_f];
  31050. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31051. return false;
  31052. }
  31053. }
  31054. return true;
  31055. };
  31056. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31057. /**
  31058. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31059. * This property is pertinent only for updatable parametric shapes.
  31060. */
  31061. get: function () {
  31062. return this._areNormalsFrozen;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. /**
  31068. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31069. * It has no effect at all on other shapes.
  31070. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31071. * Returns the Mesh.
  31072. */
  31073. Mesh.prototype.freezeNormals = function () {
  31074. this._areNormalsFrozen = true;
  31075. return this;
  31076. };
  31077. /**
  31078. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31079. * It has no effect at all on other shapes.
  31080. * It reactivates the mesh normals computation if it was previously frozen.
  31081. * Returns the Mesh.
  31082. */
  31083. Mesh.prototype.unfreezeNormals = function () {
  31084. this._areNormalsFrozen = false;
  31085. return this;
  31086. };
  31087. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31088. /**
  31089. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31090. */
  31091. set: function (count) {
  31092. this._overridenInstanceCount = count;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. // Methods
  31098. Mesh.prototype._preActivate = function () {
  31099. var sceneRenderId = this.getScene().getRenderId();
  31100. if (this._preActivateId === sceneRenderId) {
  31101. return this;
  31102. }
  31103. this._preActivateId = sceneRenderId;
  31104. this._visibleInstances = null;
  31105. return this;
  31106. };
  31107. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31108. if (this._visibleInstances) {
  31109. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31110. }
  31111. return this;
  31112. };
  31113. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31114. if (!this._visibleInstances) {
  31115. this._visibleInstances = {};
  31116. this._visibleInstances.defaultRenderId = renderId;
  31117. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31118. }
  31119. if (!this._visibleInstances[renderId]) {
  31120. this._visibleInstances[renderId] = new Array();
  31121. }
  31122. this._visibleInstances[renderId].push(instance);
  31123. return this;
  31124. };
  31125. /**
  31126. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31127. * This means the mesh underlying bounding box and sphere are recomputed.
  31128. * Returns the Mesh.
  31129. */
  31130. Mesh.prototype.refreshBoundingInfo = function () {
  31131. return this._refreshBoundingInfo(false);
  31132. };
  31133. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31134. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31135. return this;
  31136. }
  31137. var data = this._getPositionData(applySkeleton);
  31138. if (data) {
  31139. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31140. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31141. }
  31142. if (this.subMeshes) {
  31143. for (var index = 0; index < this.subMeshes.length; index++) {
  31144. this.subMeshes[index].refreshBoundingInfo();
  31145. }
  31146. }
  31147. this._updateBoundingInfo();
  31148. return this;
  31149. };
  31150. Mesh.prototype._getPositionData = function (applySkeleton) {
  31151. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31152. if (data && applySkeleton && this.skeleton) {
  31153. data = BABYLON.Tools.Slice(data);
  31154. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31155. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31156. if (matricesWeightsData && matricesIndicesData) {
  31157. var needExtras = this.numBoneInfluencers > 4;
  31158. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31159. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31160. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31161. var tempVector = BABYLON.Tmp.Vector3[0];
  31162. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31163. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31164. var matWeightIdx = 0;
  31165. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31166. finalMatrix.reset();
  31167. var inf;
  31168. var weight;
  31169. for (inf = 0; inf < 4; inf++) {
  31170. weight = matricesWeightsData[matWeightIdx + inf];
  31171. if (weight <= 0)
  31172. break;
  31173. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31174. finalMatrix.addToSelf(tempMatrix);
  31175. }
  31176. if (needExtras) {
  31177. for (inf = 0; inf < 4; inf++) {
  31178. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31179. if (weight <= 0)
  31180. break;
  31181. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31182. finalMatrix.addToSelf(tempMatrix);
  31183. }
  31184. }
  31185. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31186. tempVector.toArray(data, index);
  31187. }
  31188. }
  31189. }
  31190. return data;
  31191. };
  31192. Mesh.prototype._createGlobalSubMesh = function (force) {
  31193. var totalVertices = this.getTotalVertices();
  31194. if (!totalVertices || !this.getIndices()) {
  31195. return null;
  31196. }
  31197. // Check if we need to recreate the submeshes
  31198. if (this.subMeshes && this.subMeshes.length > 0) {
  31199. var ib = this.getIndices();
  31200. if (!ib) {
  31201. return null;
  31202. }
  31203. var totalIndices = ib.length;
  31204. var needToRecreate = false;
  31205. if (force) {
  31206. needToRecreate = true;
  31207. }
  31208. else {
  31209. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31210. var submesh = _a[_i];
  31211. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31212. needToRecreate = true;
  31213. break;
  31214. }
  31215. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31216. needToRecreate = true;
  31217. break;
  31218. }
  31219. }
  31220. }
  31221. if (!needToRecreate) {
  31222. return this.subMeshes[0];
  31223. }
  31224. }
  31225. this.releaseSubMeshes();
  31226. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31227. };
  31228. Mesh.prototype.subdivide = function (count) {
  31229. if (count < 1) {
  31230. return;
  31231. }
  31232. var totalIndices = this.getTotalIndices();
  31233. var subdivisionSize = (totalIndices / count) | 0;
  31234. var offset = 0;
  31235. // Ensure that subdivisionSize is a multiple of 3
  31236. while (subdivisionSize % 3 !== 0) {
  31237. subdivisionSize++;
  31238. }
  31239. this.releaseSubMeshes();
  31240. for (var index = 0; index < count; index++) {
  31241. if (offset >= totalIndices) {
  31242. break;
  31243. }
  31244. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31245. offset += subdivisionSize;
  31246. }
  31247. this.synchronizeInstances();
  31248. };
  31249. /**
  31250. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31251. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31252. * The `data` are either a numeric array either a Float32Array.
  31253. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31254. * 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).
  31255. * Note that a new underlying VertexBuffer object is created each call.
  31256. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31257. *
  31258. * Possible `kind` values :
  31259. * - BABYLON.VertexBuffer.PositionKind
  31260. * - BABYLON.VertexBuffer.UVKind
  31261. * - BABYLON.VertexBuffer.UV2Kind
  31262. * - BABYLON.VertexBuffer.UV3Kind
  31263. * - BABYLON.VertexBuffer.UV4Kind
  31264. * - BABYLON.VertexBuffer.UV5Kind
  31265. * - BABYLON.VertexBuffer.UV6Kind
  31266. * - BABYLON.VertexBuffer.ColorKind
  31267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31271. *
  31272. * Returns the Mesh.
  31273. */
  31274. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31275. if (updatable === void 0) { updatable = false; }
  31276. if (!this._geometry) {
  31277. var vertexData = new BABYLON.VertexData();
  31278. vertexData.set(data, kind);
  31279. var scene = this.getScene();
  31280. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31281. }
  31282. else {
  31283. this._geometry.setVerticesData(kind, data, updatable, stride);
  31284. }
  31285. return this;
  31286. };
  31287. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31288. if (updatable === void 0) { updatable = true; }
  31289. var vb = this.getVertexBuffer(kind);
  31290. if (!vb || vb.isUpdatable() === updatable) {
  31291. return;
  31292. }
  31293. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31294. };
  31295. /**
  31296. * Sets the mesh VertexBuffer.
  31297. * Returns the Mesh.
  31298. */
  31299. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31300. if (!this._geometry) {
  31301. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31302. }
  31303. this._geometry.setVerticesBuffer(buffer);
  31304. return this;
  31305. };
  31306. /**
  31307. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31308. * If the mesh has no geometry, it is simply returned as it is.
  31309. * The `data` are either a numeric array either a Float32Array.
  31310. * No new underlying VertexBuffer object is created.
  31311. * 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.
  31312. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31313. *
  31314. * Possible `kind` values :
  31315. * - BABYLON.VertexBuffer.PositionKind
  31316. * - BABYLON.VertexBuffer.UVKind
  31317. * - BABYLON.VertexBuffer.UV2Kind
  31318. * - BABYLON.VertexBuffer.UV3Kind
  31319. * - BABYLON.VertexBuffer.UV4Kind
  31320. * - BABYLON.VertexBuffer.UV5Kind
  31321. * - BABYLON.VertexBuffer.UV6Kind
  31322. * - BABYLON.VertexBuffer.ColorKind
  31323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31327. *
  31328. * Returns the Mesh.
  31329. */
  31330. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31331. if (!this._geometry) {
  31332. return this;
  31333. }
  31334. if (!makeItUnique) {
  31335. this._geometry.updateVerticesData(kind, data, updateExtends);
  31336. }
  31337. else {
  31338. this.makeGeometryUnique();
  31339. this.updateVerticesData(kind, data, updateExtends, false);
  31340. }
  31341. return this;
  31342. };
  31343. /**
  31344. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31345. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31346. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31347. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31348. * Returns the Mesh.
  31349. */
  31350. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31351. if (computeNormals === void 0) { computeNormals = true; }
  31352. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31353. if (!positions) {
  31354. return this;
  31355. }
  31356. positionFunction(positions);
  31357. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31358. if (computeNormals) {
  31359. var indices = this.getIndices();
  31360. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31361. if (!normals) {
  31362. return this;
  31363. }
  31364. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31365. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31366. }
  31367. return this;
  31368. };
  31369. /**
  31370. * Creates a un-shared specific occurence of the geometry for the mesh.
  31371. * Returns the Mesh.
  31372. */
  31373. Mesh.prototype.makeGeometryUnique = function () {
  31374. if (!this._geometry) {
  31375. return this;
  31376. }
  31377. var oldGeometry = this._geometry;
  31378. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31379. oldGeometry.releaseForMesh(this, true);
  31380. geometry.applyToMesh(this);
  31381. return this;
  31382. };
  31383. /**
  31384. * Sets the mesh indices.
  31385. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31386. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31387. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31388. * This method creates a new index buffer each call.
  31389. * Returns the Mesh.
  31390. */
  31391. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31392. if (totalVertices === void 0) { totalVertices = null; }
  31393. if (updatable === void 0) { updatable = false; }
  31394. if (!this._geometry) {
  31395. var vertexData = new BABYLON.VertexData();
  31396. vertexData.indices = indices;
  31397. var scene = this.getScene();
  31398. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31399. }
  31400. else {
  31401. this._geometry.setIndices(indices, totalVertices, updatable);
  31402. }
  31403. return this;
  31404. };
  31405. /**
  31406. * Update the current index buffer
  31407. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31408. * Returns the Mesh.
  31409. */
  31410. Mesh.prototype.updateIndices = function (indices, offset) {
  31411. if (!this._geometry) {
  31412. return this;
  31413. }
  31414. this._geometry.updateIndices(indices, offset);
  31415. return this;
  31416. };
  31417. /**
  31418. * Invert the geometry to move from a right handed system to a left handed one.
  31419. * Returns the Mesh.
  31420. */
  31421. Mesh.prototype.toLeftHanded = function () {
  31422. if (!this._geometry) {
  31423. return this;
  31424. }
  31425. this._geometry.toLeftHanded();
  31426. return this;
  31427. };
  31428. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31429. if (!this._geometry) {
  31430. return this;
  31431. }
  31432. var engine = this.getScene().getEngine();
  31433. // Wireframe
  31434. var indexToBind;
  31435. if (this._unIndexed) {
  31436. indexToBind = null;
  31437. }
  31438. else {
  31439. switch (fillMode) {
  31440. case BABYLON.Material.PointFillMode:
  31441. indexToBind = null;
  31442. break;
  31443. case BABYLON.Material.WireFrameFillMode:
  31444. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31445. break;
  31446. default:
  31447. case BABYLON.Material.TriangleFillMode:
  31448. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31449. break;
  31450. }
  31451. }
  31452. // VBOs
  31453. this._geometry._bind(effect, indexToBind);
  31454. return this;
  31455. };
  31456. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31457. if (alternate === void 0) { alternate = false; }
  31458. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31459. return this;
  31460. }
  31461. this.onBeforeDrawObservable.notifyObservers(this);
  31462. var scene = this.getScene();
  31463. var engine = scene.getEngine();
  31464. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31465. // or triangles as points
  31466. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31467. }
  31468. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31469. // Triangles as wireframe
  31470. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31471. }
  31472. else {
  31473. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31474. }
  31475. if (scene._isAlternateRenderingEnabled && !alternate) {
  31476. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31477. if (!effect || !scene.activeCamera) {
  31478. return this;
  31479. }
  31480. scene._switchToAlternateCameraConfiguration(true);
  31481. this._effectiveMaterial.bindView(effect);
  31482. this._effectiveMaterial.bindViewProjection(effect);
  31483. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31484. this._draw(subMesh, fillMode, instancesCount, true);
  31485. engine.setViewport(scene.activeCamera.viewport);
  31486. scene._switchToAlternateCameraConfiguration(false);
  31487. this._effectiveMaterial.bindView(effect);
  31488. this._effectiveMaterial.bindViewProjection(effect);
  31489. }
  31490. return this;
  31491. };
  31492. /**
  31493. * Registers for this mesh a javascript function called just before the rendering process.
  31494. * This function is passed the current mesh.
  31495. * Return the Mesh.
  31496. */
  31497. Mesh.prototype.registerBeforeRender = function (func) {
  31498. this.onBeforeRenderObservable.add(func);
  31499. return this;
  31500. };
  31501. /**
  31502. * Disposes a previously registered javascript function called before the rendering.
  31503. * This function is passed the current mesh.
  31504. * Returns the Mesh.
  31505. */
  31506. Mesh.prototype.unregisterBeforeRender = function (func) {
  31507. this.onBeforeRenderObservable.removeCallback(func);
  31508. return this;
  31509. };
  31510. /**
  31511. * Registers for this mesh a javascript function called just after the rendering is complete.
  31512. * This function is passed the current mesh.
  31513. * Returns the Mesh.
  31514. */
  31515. Mesh.prototype.registerAfterRender = function (func) {
  31516. this.onAfterRenderObservable.add(func);
  31517. return this;
  31518. };
  31519. /**
  31520. * Disposes a previously registered javascript function called after the rendering.
  31521. * This function is passed the current mesh.
  31522. * Return the Mesh.
  31523. */
  31524. Mesh.prototype.unregisterAfterRender = function (func) {
  31525. this.onAfterRenderObservable.removeCallback(func);
  31526. return this;
  31527. };
  31528. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31529. var scene = this.getScene();
  31530. this._batchCache.mustReturn = false;
  31531. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31532. this._batchCache.visibleInstances[subMeshId] = null;
  31533. if (this._visibleInstances) {
  31534. var currentRenderId = scene.getRenderId();
  31535. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31536. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31537. var selfRenderId = this._renderId;
  31538. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31539. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31540. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31541. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31542. }
  31543. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31544. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31545. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31546. this._batchCache.mustReturn = true;
  31547. return this._batchCache;
  31548. }
  31549. if (currentRenderId !== selfRenderId) {
  31550. this._batchCache.renderSelf[subMeshId] = false;
  31551. }
  31552. }
  31553. this._renderIdForInstances[subMeshId] = currentRenderId;
  31554. }
  31555. return this._batchCache;
  31556. };
  31557. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31558. var visibleInstances = batch.visibleInstances[subMesh._id];
  31559. if (!visibleInstances) {
  31560. return this;
  31561. }
  31562. var matricesCount = visibleInstances.length + 1;
  31563. var bufferSize = matricesCount * 16 * 4;
  31564. var currentInstancesBufferSize = this._instancesBufferSize;
  31565. var instancesBuffer = this._instancesBuffer;
  31566. while (this._instancesBufferSize < bufferSize) {
  31567. this._instancesBufferSize *= 2;
  31568. }
  31569. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31570. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31571. }
  31572. var offset = 0;
  31573. var instancesCount = 0;
  31574. var world = this.getWorldMatrix();
  31575. if (batch.renderSelf[subMesh._id]) {
  31576. world.copyToArray(this._instancesData, offset);
  31577. offset += 16;
  31578. instancesCount++;
  31579. }
  31580. if (visibleInstances) {
  31581. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31582. var instance = visibleInstances[instanceIndex];
  31583. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31584. offset += 16;
  31585. instancesCount++;
  31586. }
  31587. }
  31588. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31589. if (instancesBuffer) {
  31590. instancesBuffer.dispose();
  31591. }
  31592. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31593. this._instancesBuffer = instancesBuffer;
  31594. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31595. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31596. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31597. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31598. }
  31599. else {
  31600. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31601. }
  31602. this._bind(subMesh, effect, fillMode);
  31603. this._draw(subMesh, fillMode, instancesCount);
  31604. engine.unbindInstanceAttributes();
  31605. return this;
  31606. };
  31607. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31608. var scene = this.getScene();
  31609. var engine = scene.getEngine();
  31610. if (hardwareInstancedRendering) {
  31611. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31612. }
  31613. else {
  31614. if (batch.renderSelf[subMesh._id]) {
  31615. // Draw
  31616. if (onBeforeDraw) {
  31617. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31618. }
  31619. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31620. }
  31621. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31622. if (visibleInstancesForSubMesh) {
  31623. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31624. var instance = visibleInstancesForSubMesh[instanceIndex];
  31625. // World
  31626. var world = instance.getWorldMatrix();
  31627. if (onBeforeDraw) {
  31628. onBeforeDraw(true, world, effectiveMaterial);
  31629. }
  31630. // Draw
  31631. this._draw(subMesh, fillMode);
  31632. }
  31633. }
  31634. }
  31635. return this;
  31636. };
  31637. /**
  31638. * Triggers the draw call for the mesh.
  31639. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31640. * Returns the Mesh.
  31641. */
  31642. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31643. this.checkOcclusionQuery();
  31644. if (this._isOccluded) {
  31645. return this;
  31646. }
  31647. var scene = this.getScene();
  31648. // Managing instances
  31649. var batch = this._getInstancesRenderList(subMesh._id);
  31650. if (batch.mustReturn) {
  31651. return this;
  31652. }
  31653. // Checking geometry state
  31654. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31655. return this;
  31656. }
  31657. this.onBeforeRenderObservable.notifyObservers(this);
  31658. var engine = scene.getEngine();
  31659. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31660. // Material
  31661. var material = subMesh.getMaterial();
  31662. if (!material) {
  31663. return this;
  31664. }
  31665. this._effectiveMaterial = material;
  31666. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31667. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31668. return this;
  31669. }
  31670. }
  31671. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31672. return this;
  31673. }
  31674. // Alpha mode
  31675. if (enableAlphaMode) {
  31676. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31677. }
  31678. // Outline - step 1
  31679. var savedDepthWrite = engine.getDepthWrite();
  31680. if (this.renderOutline) {
  31681. engine.setDepthWrite(false);
  31682. scene.getOutlineRenderer().render(subMesh, batch);
  31683. engine.setDepthWrite(savedDepthWrite);
  31684. }
  31685. var effect;
  31686. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31687. effect = subMesh.effect;
  31688. }
  31689. else {
  31690. effect = this._effectiveMaterial.getEffect();
  31691. }
  31692. if (!effect) {
  31693. return this;
  31694. }
  31695. var sideOrientation = this.overrideMaterialSideOrientation;
  31696. if (sideOrientation == null) {
  31697. sideOrientation = this._effectiveMaterial.sideOrientation;
  31698. if (this._getWorldMatrixDeterminant() < 0) {
  31699. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31700. }
  31701. }
  31702. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31703. if (this._effectiveMaterial.forceDepthWrite) {
  31704. engine.setDepthWrite(true);
  31705. }
  31706. // Bind
  31707. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31708. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31709. this._bind(subMesh, effect, fillMode);
  31710. }
  31711. var world = this.getWorldMatrix();
  31712. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31713. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31714. }
  31715. else {
  31716. this._effectiveMaterial.bind(world, this);
  31717. }
  31718. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31719. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31720. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31721. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31722. }
  31723. // Draw
  31724. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31725. // Unbind
  31726. this._effectiveMaterial.unbind();
  31727. // Outline - step 2
  31728. if (this.renderOutline && savedDepthWrite) {
  31729. engine.setDepthWrite(true);
  31730. engine.setColorWrite(false);
  31731. scene.getOutlineRenderer().render(subMesh, batch);
  31732. engine.setColorWrite(true);
  31733. }
  31734. // Overlay
  31735. if (this.renderOverlay) {
  31736. var currentMode = engine.getAlphaMode();
  31737. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31738. scene.getOutlineRenderer().render(subMesh, batch, true);
  31739. engine.setAlphaMode(currentMode);
  31740. }
  31741. this.onAfterRenderObservable.notifyObservers(this);
  31742. return this;
  31743. };
  31744. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31745. if (isInstance && effectiveMaterial) {
  31746. effectiveMaterial.bindOnlyWorldMatrix(world);
  31747. }
  31748. };
  31749. /**
  31750. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31751. */
  31752. Mesh.prototype.getEmittedParticleSystems = function () {
  31753. var results = new Array();
  31754. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31755. var particleSystem = this.getScene().particleSystems[index];
  31756. if (particleSystem.emitter === this) {
  31757. results.push(particleSystem);
  31758. }
  31759. }
  31760. return results;
  31761. };
  31762. /**
  31763. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31764. */
  31765. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31766. var results = new Array();
  31767. var descendants = this.getDescendants();
  31768. descendants.push(this);
  31769. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31770. var particleSystem = this.getScene().particleSystems[index];
  31771. var emitter = particleSystem.emitter;
  31772. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31773. results.push(particleSystem);
  31774. }
  31775. }
  31776. return results;
  31777. };
  31778. Mesh.prototype._checkDelayState = function () {
  31779. var scene = this.getScene();
  31780. if (this._geometry) {
  31781. this._geometry.load(scene);
  31782. }
  31783. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31784. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31785. this._queueLoad(scene);
  31786. }
  31787. return this;
  31788. };
  31789. Mesh.prototype._queueLoad = function (scene) {
  31790. var _this = this;
  31791. scene._addPendingData(this);
  31792. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31793. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31794. if (data instanceof ArrayBuffer) {
  31795. _this._delayLoadingFunction(data, _this);
  31796. }
  31797. else {
  31798. _this._delayLoadingFunction(JSON.parse(data), _this);
  31799. }
  31800. _this.instances.forEach(function (instance) {
  31801. instance._syncSubMeshes();
  31802. });
  31803. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31804. scene._removePendingData(_this);
  31805. }, function () { }, scene.database, getBinaryData);
  31806. return this;
  31807. };
  31808. /**
  31809. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31810. */
  31811. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31812. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31813. return false;
  31814. }
  31815. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31816. return false;
  31817. }
  31818. this._checkDelayState();
  31819. return true;
  31820. };
  31821. /**
  31822. * Sets the mesh material by the material or multiMaterial `id` property.
  31823. * The material `id` is a string identifying the material or the multiMaterial.
  31824. * This method returns the Mesh.
  31825. */
  31826. Mesh.prototype.setMaterialByID = function (id) {
  31827. var materials = this.getScene().materials;
  31828. var index;
  31829. for (index = materials.length - 1; index > -1; index--) {
  31830. if (materials[index].id === id) {
  31831. this.material = materials[index];
  31832. return this;
  31833. }
  31834. }
  31835. // Multi
  31836. var multiMaterials = this.getScene().multiMaterials;
  31837. for (index = multiMaterials.length - 1; index > -1; index--) {
  31838. if (multiMaterials[index].id === id) {
  31839. this.material = multiMaterials[index];
  31840. return this;
  31841. }
  31842. }
  31843. return this;
  31844. };
  31845. /**
  31846. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31847. */
  31848. Mesh.prototype.getAnimatables = function () {
  31849. var results = new Array();
  31850. if (this.material) {
  31851. results.push(this.material);
  31852. }
  31853. if (this.skeleton) {
  31854. results.push(this.skeleton);
  31855. }
  31856. return results;
  31857. };
  31858. /**
  31859. * Modifies the mesh geometry according to the passed transformation matrix.
  31860. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31861. * The mesh normals are modified accordingly the same transformation.
  31862. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31863. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31864. * Returns the Mesh.
  31865. */
  31866. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31867. // Position
  31868. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31869. return this;
  31870. }
  31871. var submeshes = this.subMeshes.splice(0);
  31872. this._resetPointsArrayCache();
  31873. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31874. var temp = new Array();
  31875. var index;
  31876. for (index = 0; index < data.length; index += 3) {
  31877. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31878. }
  31879. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31880. // Normals
  31881. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31882. return this;
  31883. }
  31884. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31885. temp = [];
  31886. for (index = 0; index < data.length; index += 3) {
  31887. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31888. }
  31889. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31890. // flip faces?
  31891. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31892. this.flipFaces();
  31893. }
  31894. // Restore submeshes
  31895. this.releaseSubMeshes();
  31896. this.subMeshes = submeshes;
  31897. return this;
  31898. };
  31899. /**
  31900. * Modifies the mesh geometry according to its own current World Matrix.
  31901. * The mesh World Matrix is then reset.
  31902. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31903. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31904. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31905. * Returns the Mesh.
  31906. */
  31907. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31908. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31909. this.scaling.copyFromFloats(1, 1, 1);
  31910. this.position.copyFromFloats(0, 0, 0);
  31911. this.rotation.copyFromFloats(0, 0, 0);
  31912. //only if quaternion is already set
  31913. if (this.rotationQuaternion) {
  31914. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31915. }
  31916. this._worldMatrix = BABYLON.Matrix.Identity();
  31917. return this;
  31918. };
  31919. Object.defineProperty(Mesh.prototype, "_positions", {
  31920. // Cache
  31921. get: function () {
  31922. if (this._geometry) {
  31923. return this._geometry._positions;
  31924. }
  31925. return null;
  31926. },
  31927. enumerable: true,
  31928. configurable: true
  31929. });
  31930. Mesh.prototype._resetPointsArrayCache = function () {
  31931. if (this._geometry) {
  31932. this._geometry._resetPointsArrayCache();
  31933. }
  31934. return this;
  31935. };
  31936. Mesh.prototype._generatePointsArray = function () {
  31937. if (this._geometry) {
  31938. return this._geometry._generatePointsArray();
  31939. }
  31940. return false;
  31941. };
  31942. /**
  31943. * Returns a new Mesh object generated from the current mesh properties.
  31944. * This method must not get confused with createInstance().
  31945. * The parameter `name` is a string, the name given to the new mesh.
  31946. * The optional parameter `newParent` can be any Node object (default `null`).
  31947. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31948. * 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.
  31949. */
  31950. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31951. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31952. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31953. };
  31954. /**
  31955. * Releases resources associated with this mesh.
  31956. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31957. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31958. */
  31959. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31960. var _this = this;
  31961. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31962. this.morphTargetManager = null;
  31963. if (this._geometry) {
  31964. this._geometry.releaseForMesh(this, true);
  31965. }
  31966. // Sources
  31967. var meshes = this.getScene().meshes;
  31968. meshes.forEach(function (abstractMesh) {
  31969. var mesh = abstractMesh;
  31970. if (mesh._source && mesh._source === _this) {
  31971. mesh._source = null;
  31972. }
  31973. });
  31974. this._source = null;
  31975. // Instances
  31976. if (this._instancesBuffer) {
  31977. this._instancesBuffer.dispose();
  31978. this._instancesBuffer = null;
  31979. }
  31980. while (this.instances.length) {
  31981. this.instances[0].dispose();
  31982. }
  31983. // Effect layers.
  31984. var effectLayers = this.getScene().effectLayers;
  31985. for (var i = 0; i < effectLayers.length; i++) {
  31986. var effectLayer = effectLayers[i];
  31987. if (effectLayer) {
  31988. effectLayer._disposeMesh(this);
  31989. }
  31990. }
  31991. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31992. };
  31993. /**
  31994. * Modifies the mesh geometry according to a displacement map.
  31995. * 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.
  31996. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31997. * This method returns nothing.
  31998. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31999. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32000. * 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.
  32001. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32002. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32003. *
  32004. * Returns the Mesh.
  32005. */
  32006. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32007. var _this = this;
  32008. var scene = this.getScene();
  32009. var onload = function (img) {
  32010. // Getting height map data
  32011. var canvas = document.createElement("canvas");
  32012. var context = canvas.getContext("2d");
  32013. var heightMapWidth = img.width;
  32014. var heightMapHeight = img.height;
  32015. canvas.width = heightMapWidth;
  32016. canvas.height = heightMapHeight;
  32017. context.drawImage(img, 0, 0);
  32018. // Create VertexData from map data
  32019. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32020. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32021. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32022. //execute success callback, if set
  32023. if (onSuccess) {
  32024. onSuccess(_this);
  32025. }
  32026. };
  32027. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32028. return this;
  32029. };
  32030. /**
  32031. * Modifies the mesh geometry according to a displacementMap buffer.
  32032. * 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.
  32033. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32034. * This method returns nothing.
  32035. * 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.
  32036. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32037. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32038. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32039. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32040. *
  32041. * Returns the Mesh.
  32042. */
  32043. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32044. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32045. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32046. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32047. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32048. return this;
  32049. }
  32050. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32051. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32052. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32053. var position = BABYLON.Vector3.Zero();
  32054. var normal = BABYLON.Vector3.Zero();
  32055. var uv = BABYLON.Vector2.Zero();
  32056. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32057. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32058. for (var index = 0; index < positions.length; index += 3) {
  32059. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32060. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32061. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32062. // Compute height
  32063. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32064. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32065. var pos = (u + v * heightMapWidth) * 4;
  32066. var r = buffer[pos] / 255.0;
  32067. var g = buffer[pos + 1] / 255.0;
  32068. var b = buffer[pos + 2] / 255.0;
  32069. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32070. normal.normalize();
  32071. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32072. position = position.add(normal);
  32073. position.toArray(positions, index);
  32074. }
  32075. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32076. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32077. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32078. return this;
  32079. };
  32080. /**
  32081. * Modify the mesh to get a flat shading rendering.
  32082. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32083. * This method returns the Mesh.
  32084. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32085. */
  32086. Mesh.prototype.convertToFlatShadedMesh = function () {
  32087. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32088. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32089. var kinds = this.getVerticesDataKinds();
  32090. var vbs = {};
  32091. var data = {};
  32092. var newdata = {};
  32093. var updatableNormals = false;
  32094. var kindIndex;
  32095. var kind;
  32096. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32097. kind = kinds[kindIndex];
  32098. var vertexBuffer = this.getVertexBuffer(kind);
  32099. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32100. updatableNormals = vertexBuffer.isUpdatable();
  32101. kinds.splice(kindIndex, 1);
  32102. kindIndex--;
  32103. continue;
  32104. }
  32105. vbs[kind] = vertexBuffer;
  32106. data[kind] = vbs[kind].getData();
  32107. newdata[kind] = [];
  32108. }
  32109. // Save previous submeshes
  32110. var previousSubmeshes = this.subMeshes.slice(0);
  32111. var indices = this.getIndices();
  32112. var totalIndices = this.getTotalIndices();
  32113. // Generating unique vertices per face
  32114. var index;
  32115. for (index = 0; index < totalIndices; index++) {
  32116. var vertexIndex = indices[index];
  32117. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32118. kind = kinds[kindIndex];
  32119. var stride = vbs[kind].getStrideSize();
  32120. for (var offset = 0; offset < stride; offset++) {
  32121. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32122. }
  32123. }
  32124. }
  32125. // Updating faces & normal
  32126. var normals = [];
  32127. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32128. for (index = 0; index < totalIndices; index += 3) {
  32129. indices[index] = index;
  32130. indices[index + 1] = index + 1;
  32131. indices[index + 2] = index + 2;
  32132. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32133. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32134. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32135. var p1p2 = p1.subtract(p2);
  32136. var p3p2 = p3.subtract(p2);
  32137. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32138. // Store same normals for every vertex
  32139. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32140. normals.push(normal.x);
  32141. normals.push(normal.y);
  32142. normals.push(normal.z);
  32143. }
  32144. }
  32145. this.setIndices(indices);
  32146. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32147. // Updating vertex buffers
  32148. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32149. kind = kinds[kindIndex];
  32150. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32151. }
  32152. // Updating submeshes
  32153. this.releaseSubMeshes();
  32154. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32155. var previousOne = previousSubmeshes[submeshIndex];
  32156. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32157. }
  32158. this.synchronizeInstances();
  32159. return this;
  32160. };
  32161. /**
  32162. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32163. * In other words, more vertices, no more indices and a single bigger VBO.
  32164. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32165. * Returns the Mesh.
  32166. */
  32167. Mesh.prototype.convertToUnIndexedMesh = function () {
  32168. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32169. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32170. var kinds = this.getVerticesDataKinds();
  32171. var vbs = {};
  32172. var data = {};
  32173. var newdata = {};
  32174. var kindIndex;
  32175. var kind;
  32176. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32177. kind = kinds[kindIndex];
  32178. var vertexBuffer = this.getVertexBuffer(kind);
  32179. vbs[kind] = vertexBuffer;
  32180. data[kind] = vbs[kind].getData();
  32181. newdata[kind] = [];
  32182. }
  32183. // Save previous submeshes
  32184. var previousSubmeshes = this.subMeshes.slice(0);
  32185. var indices = this.getIndices();
  32186. var totalIndices = this.getTotalIndices();
  32187. // Generating unique vertices per face
  32188. var index;
  32189. for (index = 0; index < totalIndices; index++) {
  32190. var vertexIndex = indices[index];
  32191. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32192. kind = kinds[kindIndex];
  32193. var stride = vbs[kind].getStrideSize();
  32194. for (var offset = 0; offset < stride; offset++) {
  32195. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32196. }
  32197. }
  32198. }
  32199. // Updating indices
  32200. for (index = 0; index < totalIndices; index += 3) {
  32201. indices[index] = index;
  32202. indices[index + 1] = index + 1;
  32203. indices[index + 2] = index + 2;
  32204. }
  32205. this.setIndices(indices);
  32206. // Updating vertex buffers
  32207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32208. kind = kinds[kindIndex];
  32209. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32210. }
  32211. // Updating submeshes
  32212. this.releaseSubMeshes();
  32213. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32214. var previousOne = previousSubmeshes[submeshIndex];
  32215. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32216. }
  32217. this._unIndexed = true;
  32218. this.synchronizeInstances();
  32219. return this;
  32220. };
  32221. /**
  32222. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32223. * This method returns the Mesh.
  32224. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32225. */
  32226. Mesh.prototype.flipFaces = function (flipNormals) {
  32227. if (flipNormals === void 0) { flipNormals = false; }
  32228. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32229. var i;
  32230. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32231. for (i = 0; i < vertex_data.normals.length; i++) {
  32232. vertex_data.normals[i] *= -1;
  32233. }
  32234. }
  32235. if (vertex_data.indices) {
  32236. var temp;
  32237. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32238. // reassign indices
  32239. temp = vertex_data.indices[i + 1];
  32240. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32241. vertex_data.indices[i + 2] = temp;
  32242. }
  32243. }
  32244. vertex_data.applyToMesh(this);
  32245. return this;
  32246. };
  32247. // Instances
  32248. /**
  32249. * Creates a new InstancedMesh object from the mesh model.
  32250. * An instance shares the same properties and the same material than its model.
  32251. * Only these properties of each instance can then be set individually :
  32252. * - position
  32253. * - rotation
  32254. * - rotationQuaternion
  32255. * - setPivotMatrix
  32256. * - scaling
  32257. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32258. * Warning : this method is not supported for Line mesh and LineSystem
  32259. */
  32260. Mesh.prototype.createInstance = function (name) {
  32261. return new BABYLON.InstancedMesh(name, this);
  32262. };
  32263. /**
  32264. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32265. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32266. * This method returns the Mesh.
  32267. */
  32268. Mesh.prototype.synchronizeInstances = function () {
  32269. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32270. var instance = this.instances[instanceIndex];
  32271. instance._syncSubMeshes();
  32272. }
  32273. return this;
  32274. };
  32275. /**
  32276. * Simplify the mesh according to the given array of settings.
  32277. * Function will return immediately and will simplify async. It returns the Mesh.
  32278. * @param settings a collection of simplification settings.
  32279. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32280. * @param type the type of simplification to run.
  32281. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32282. */
  32283. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32284. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32285. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32286. this.getScene().simplificationQueue.addTask({
  32287. settings: settings,
  32288. parallelProcessing: parallelProcessing,
  32289. mesh: this,
  32290. simplificationType: simplificationType,
  32291. successCallback: successCallback
  32292. });
  32293. return this;
  32294. };
  32295. /**
  32296. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32297. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32298. * This should be used together with the simplification to avoid disappearing triangles.
  32299. * Returns the Mesh.
  32300. * @param successCallback an optional success callback to be called after the optimization finished.
  32301. */
  32302. Mesh.prototype.optimizeIndices = function (successCallback) {
  32303. var _this = this;
  32304. var indices = this.getIndices();
  32305. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32306. if (!positions || !indices) {
  32307. return this;
  32308. }
  32309. var vectorPositions = new Array();
  32310. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32311. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32312. }
  32313. var dupes = new Array();
  32314. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32315. var realPos = vectorPositions.length - 1 - iteration;
  32316. var testedPosition = vectorPositions[realPos];
  32317. for (var j = 0; j < realPos; ++j) {
  32318. var againstPosition = vectorPositions[j];
  32319. if (testedPosition.equals(againstPosition)) {
  32320. dupes[realPos] = j;
  32321. break;
  32322. }
  32323. }
  32324. }, function () {
  32325. for (var i = 0; i < indices.length; ++i) {
  32326. indices[i] = dupes[indices[i]] || indices[i];
  32327. }
  32328. //indices are now reordered
  32329. var originalSubMeshes = _this.subMeshes.slice(0);
  32330. _this.setIndices(indices);
  32331. _this.subMeshes = originalSubMeshes;
  32332. if (successCallback) {
  32333. successCallback(_this);
  32334. }
  32335. });
  32336. return this;
  32337. };
  32338. Mesh.prototype.serialize = function (serializationObject) {
  32339. serializationObject.name = this.name;
  32340. serializationObject.id = this.id;
  32341. serializationObject.type = this.getClassName();
  32342. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32343. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32344. }
  32345. serializationObject.position = this.position.asArray();
  32346. if (this.rotationQuaternion) {
  32347. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32348. }
  32349. else if (this.rotation) {
  32350. serializationObject.rotation = this.rotation.asArray();
  32351. }
  32352. serializationObject.scaling = this.scaling.asArray();
  32353. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32354. serializationObject.isEnabled = this.isEnabled(false);
  32355. serializationObject.isVisible = this.isVisible;
  32356. serializationObject.infiniteDistance = this.infiniteDistance;
  32357. serializationObject.pickable = this.isPickable;
  32358. serializationObject.receiveShadows = this.receiveShadows;
  32359. serializationObject.billboardMode = this.billboardMode;
  32360. serializationObject.visibility = this.visibility;
  32361. serializationObject.checkCollisions = this.checkCollisions;
  32362. serializationObject.isBlocker = this.isBlocker;
  32363. // Parent
  32364. if (this.parent) {
  32365. serializationObject.parentId = this.parent.id;
  32366. }
  32367. // Geometry
  32368. serializationObject.isUnIndexed = this.isUnIndexed;
  32369. var geometry = this._geometry;
  32370. if (geometry) {
  32371. var geometryId = geometry.id;
  32372. serializationObject.geometryId = geometryId;
  32373. // SubMeshes
  32374. serializationObject.subMeshes = [];
  32375. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32376. var subMesh = this.subMeshes[subIndex];
  32377. serializationObject.subMeshes.push({
  32378. materialIndex: subMesh.materialIndex,
  32379. verticesStart: subMesh.verticesStart,
  32380. verticesCount: subMesh.verticesCount,
  32381. indexStart: subMesh.indexStart,
  32382. indexCount: subMesh.indexCount
  32383. });
  32384. }
  32385. }
  32386. // Material
  32387. if (this.material) {
  32388. serializationObject.materialId = this.material.id;
  32389. }
  32390. else {
  32391. this.material = null;
  32392. }
  32393. // Morph targets
  32394. if (this.morphTargetManager) {
  32395. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32396. }
  32397. // Skeleton
  32398. if (this.skeleton) {
  32399. serializationObject.skeletonId = this.skeleton.id;
  32400. }
  32401. // Physics
  32402. //TODO implement correct serialization for physics impostors.
  32403. var impostor = this.getPhysicsImpostor();
  32404. if (impostor) {
  32405. serializationObject.physicsMass = impostor.getParam("mass");
  32406. serializationObject.physicsFriction = impostor.getParam("friction");
  32407. serializationObject.physicsRestitution = impostor.getParam("mass");
  32408. serializationObject.physicsImpostor = impostor.type;
  32409. }
  32410. // Metadata
  32411. if (this.metadata) {
  32412. serializationObject.metadata = this.metadata;
  32413. }
  32414. // Instances
  32415. serializationObject.instances = [];
  32416. for (var index = 0; index < this.instances.length; index++) {
  32417. var instance = this.instances[index];
  32418. var serializationInstance = {
  32419. name: instance.name,
  32420. id: instance.id,
  32421. position: instance.position.asArray(),
  32422. scaling: instance.scaling.asArray()
  32423. };
  32424. if (instance.rotationQuaternion) {
  32425. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32426. }
  32427. else if (instance.rotation) {
  32428. serializationInstance.rotation = instance.rotation.asArray();
  32429. }
  32430. serializationObject.instances.push(serializationInstance);
  32431. // Animations
  32432. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32433. serializationInstance.ranges = instance.serializeAnimationRanges();
  32434. }
  32435. //
  32436. // Animations
  32437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32438. serializationObject.ranges = this.serializeAnimationRanges();
  32439. // Layer mask
  32440. serializationObject.layerMask = this.layerMask;
  32441. // Alpha
  32442. serializationObject.alphaIndex = this.alphaIndex;
  32443. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32444. // Overlay
  32445. serializationObject.overlayAlpha = this.overlayAlpha;
  32446. serializationObject.overlayColor = this.overlayColor.asArray();
  32447. serializationObject.renderOverlay = this.renderOverlay;
  32448. // Fog
  32449. serializationObject.applyFog = this.applyFog;
  32450. // Action Manager
  32451. if (this.actionManager) {
  32452. serializationObject.actions = this.actionManager.serialize(this.name);
  32453. }
  32454. };
  32455. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32456. if (!this.geometry) {
  32457. return;
  32458. }
  32459. this._markSubMeshesAsAttributesDirty();
  32460. var morphTargetManager = this._morphTargetManager;
  32461. if (morphTargetManager && morphTargetManager.vertexCount) {
  32462. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32463. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32464. this.morphTargetManager = null;
  32465. return;
  32466. }
  32467. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32468. var morphTarget = morphTargetManager.getActiveTarget(index);
  32469. var positions = morphTarget.getPositions();
  32470. if (!positions) {
  32471. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32472. return;
  32473. }
  32474. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32475. var normals = morphTarget.getNormals();
  32476. if (normals) {
  32477. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32478. }
  32479. var tangents = morphTarget.getTangents();
  32480. if (tangents) {
  32481. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32482. }
  32483. }
  32484. }
  32485. else {
  32486. var index = 0;
  32487. // Positions
  32488. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32489. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32490. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32491. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32492. }
  32493. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32494. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32495. }
  32496. index++;
  32497. }
  32498. }
  32499. };
  32500. // Statics
  32501. /**
  32502. * Returns a new Mesh object parsed from the source provided.
  32503. * The parameter `parsedMesh` is the source.
  32504. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32505. */
  32506. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32507. var mesh;
  32508. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32509. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32510. }
  32511. else {
  32512. mesh = new Mesh(parsedMesh.name, scene);
  32513. }
  32514. mesh.id = parsedMesh.id;
  32515. if (BABYLON.Tags) {
  32516. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32517. }
  32518. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32519. if (parsedMesh.metadata !== undefined) {
  32520. mesh.metadata = parsedMesh.metadata;
  32521. }
  32522. if (parsedMesh.rotationQuaternion) {
  32523. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32524. }
  32525. else if (parsedMesh.rotation) {
  32526. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32527. }
  32528. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32529. if (parsedMesh.localMatrix) {
  32530. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32531. }
  32532. else if (parsedMesh.pivotMatrix) {
  32533. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32534. }
  32535. mesh.setEnabled(parsedMesh.isEnabled);
  32536. mesh.isVisible = parsedMesh.isVisible;
  32537. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32538. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32539. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32540. if (parsedMesh.applyFog !== undefined) {
  32541. mesh.applyFog = parsedMesh.applyFog;
  32542. }
  32543. if (parsedMesh.pickable !== undefined) {
  32544. mesh.isPickable = parsedMesh.pickable;
  32545. }
  32546. if (parsedMesh.alphaIndex !== undefined) {
  32547. mesh.alphaIndex = parsedMesh.alphaIndex;
  32548. }
  32549. mesh.receiveShadows = parsedMesh.receiveShadows;
  32550. mesh.billboardMode = parsedMesh.billboardMode;
  32551. if (parsedMesh.visibility !== undefined) {
  32552. mesh.visibility = parsedMesh.visibility;
  32553. }
  32554. mesh.checkCollisions = parsedMesh.checkCollisions;
  32555. if (parsedMesh.isBlocker !== undefined) {
  32556. mesh.isBlocker = parsedMesh.isBlocker;
  32557. }
  32558. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32559. // freezeWorldMatrix
  32560. if (parsedMesh.freezeWorldMatrix) {
  32561. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32562. }
  32563. // Parent
  32564. if (parsedMesh.parentId) {
  32565. mesh._waitingParentId = parsedMesh.parentId;
  32566. }
  32567. // Actions
  32568. if (parsedMesh.actions !== undefined) {
  32569. mesh._waitingActions = parsedMesh.actions;
  32570. }
  32571. // Overlay
  32572. if (parsedMesh.overlayAlpha !== undefined) {
  32573. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32574. }
  32575. if (parsedMesh.overlayColor !== undefined) {
  32576. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32577. }
  32578. if (parsedMesh.renderOverlay !== undefined) {
  32579. mesh.renderOverlay = parsedMesh.renderOverlay;
  32580. }
  32581. // Geometry
  32582. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32583. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32584. if (parsedMesh.delayLoadingFile) {
  32585. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32586. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32587. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32588. if (parsedMesh._binaryInfo) {
  32589. mesh._binaryInfo = parsedMesh._binaryInfo;
  32590. }
  32591. mesh._delayInfo = [];
  32592. if (parsedMesh.hasUVs) {
  32593. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32594. }
  32595. if (parsedMesh.hasUVs2) {
  32596. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32597. }
  32598. if (parsedMesh.hasUVs3) {
  32599. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32600. }
  32601. if (parsedMesh.hasUVs4) {
  32602. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32603. }
  32604. if (parsedMesh.hasUVs5) {
  32605. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32606. }
  32607. if (parsedMesh.hasUVs6) {
  32608. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32609. }
  32610. if (parsedMesh.hasColors) {
  32611. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32612. }
  32613. if (parsedMesh.hasMatricesIndices) {
  32614. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32615. }
  32616. if (parsedMesh.hasMatricesWeights) {
  32617. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32618. }
  32619. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32620. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32621. mesh._checkDelayState();
  32622. }
  32623. }
  32624. else {
  32625. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32626. }
  32627. // Material
  32628. if (parsedMesh.materialId) {
  32629. mesh.setMaterialByID(parsedMesh.materialId);
  32630. }
  32631. else {
  32632. mesh.material = null;
  32633. }
  32634. // Morph targets
  32635. if (parsedMesh.morphTargetManagerId > -1) {
  32636. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32637. }
  32638. // Skeleton
  32639. if (parsedMesh.skeletonId > -1) {
  32640. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32641. if (parsedMesh.numBoneInfluencers) {
  32642. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32643. }
  32644. }
  32645. // Animations
  32646. if (parsedMesh.animations) {
  32647. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32648. var parsedAnimation = parsedMesh.animations[animationIndex];
  32649. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32650. }
  32651. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32652. }
  32653. if (parsedMesh.autoAnimate) {
  32654. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32655. }
  32656. // Layer Mask
  32657. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32658. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32659. }
  32660. else {
  32661. mesh.layerMask = 0x0FFFFFFF;
  32662. }
  32663. // Physics
  32664. if (parsedMesh.physicsImpostor) {
  32665. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32666. mass: parsedMesh.physicsMass,
  32667. friction: parsedMesh.physicsFriction,
  32668. restitution: parsedMesh.physicsRestitution
  32669. }, scene);
  32670. }
  32671. // Instances
  32672. if (parsedMesh.instances) {
  32673. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32674. var parsedInstance = parsedMesh.instances[index];
  32675. var instance = mesh.createInstance(parsedInstance.name);
  32676. if (parsedInstance.id) {
  32677. instance.id = parsedInstance.id;
  32678. }
  32679. if (BABYLON.Tags) {
  32680. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32681. }
  32682. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32683. if (parsedInstance.parentId) {
  32684. instance._waitingParentId = parsedInstance.parentId;
  32685. }
  32686. if (parsedInstance.rotationQuaternion) {
  32687. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32688. }
  32689. else if (parsedInstance.rotation) {
  32690. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32691. }
  32692. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32693. instance.checkCollisions = mesh.checkCollisions;
  32694. if (parsedMesh.animations) {
  32695. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32696. parsedAnimation = parsedMesh.animations[animationIndex];
  32697. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32698. }
  32699. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32700. }
  32701. }
  32702. }
  32703. return mesh;
  32704. };
  32705. /**
  32706. * Creates a ribbon mesh.
  32707. * Please consider using the same method from the MeshBuilder class instead.
  32708. * 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.
  32709. *
  32710. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32711. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32712. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32713. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32714. * 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.
  32715. * 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.
  32716. * 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
  32717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32720. */
  32721. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32722. if (closeArray === void 0) { closeArray = false; }
  32723. if (updatable === void 0) { updatable = false; }
  32724. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32725. pathArray: pathArray,
  32726. closeArray: closeArray,
  32727. closePath: closePath,
  32728. offset: offset,
  32729. updatable: updatable,
  32730. sideOrientation: sideOrientation,
  32731. instance: instance
  32732. }, scene);
  32733. };
  32734. /**
  32735. * Creates a plane polygonal mesh. By default, this is a disc.
  32736. * Please consider using the same method from the MeshBuilder class instead.
  32737. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32738. * 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.
  32739. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32740. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32742. */
  32743. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32744. if (scene === void 0) { scene = null; }
  32745. var options = {
  32746. radius: radius,
  32747. tessellation: tessellation,
  32748. sideOrientation: sideOrientation,
  32749. updatable: updatable
  32750. };
  32751. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32752. };
  32753. /**
  32754. * Creates a box mesh.
  32755. * Please consider using the same method from the MeshBuilder class instead.
  32756. * The parameter `size` sets the size (float) of each box side (default 1).
  32757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32760. */
  32761. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32762. if (scene === void 0) { scene = null; }
  32763. var options = {
  32764. size: size,
  32765. sideOrientation: sideOrientation,
  32766. updatable: updatable
  32767. };
  32768. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32769. };
  32770. /**
  32771. * Creates a sphere mesh.
  32772. * Please consider using the same method from the MeshBuilder class instead.
  32773. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32774. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32778. */
  32779. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32780. var options = {
  32781. segments: segments,
  32782. diameterX: diameter,
  32783. diameterY: diameter,
  32784. diameterZ: diameter,
  32785. sideOrientation: sideOrientation,
  32786. updatable: updatable
  32787. };
  32788. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32789. };
  32790. /**
  32791. * Creates a cylinder or a cone mesh.
  32792. * Please consider using the same method from the MeshBuilder class instead.
  32793. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32794. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32795. * 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.
  32796. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32797. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32801. */
  32802. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32803. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32804. if (scene !== undefined) {
  32805. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32806. updatable = scene;
  32807. }
  32808. scene = subdivisions;
  32809. subdivisions = 1;
  32810. }
  32811. var options = {
  32812. height: height,
  32813. diameterTop: diameterTop,
  32814. diameterBottom: diameterBottom,
  32815. tessellation: tessellation,
  32816. subdivisions: subdivisions,
  32817. sideOrientation: sideOrientation,
  32818. updatable: updatable
  32819. };
  32820. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32821. };
  32822. // Torus (Code from SharpDX.org)
  32823. /**
  32824. * Creates a torus mesh.
  32825. * Please consider using the same method from the MeshBuilder class instead.
  32826. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32827. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32828. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32832. */
  32833. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32834. var options = {
  32835. diameter: diameter,
  32836. thickness: thickness,
  32837. tessellation: tessellation,
  32838. sideOrientation: sideOrientation,
  32839. updatable: updatable
  32840. };
  32841. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32842. };
  32843. /**
  32844. * Creates a torus knot mesh.
  32845. * Please consider using the same method from the MeshBuilder class instead.
  32846. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32847. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32848. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32849. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32853. */
  32854. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32855. var options = {
  32856. radius: radius,
  32857. tube: tube,
  32858. radialSegments: radialSegments,
  32859. tubularSegments: tubularSegments,
  32860. p: p,
  32861. q: q,
  32862. sideOrientation: sideOrientation,
  32863. updatable: updatable
  32864. };
  32865. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32866. };
  32867. /**
  32868. * Creates a line mesh.
  32869. * Please consider using the same method from the MeshBuilder class instead.
  32870. * 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.
  32871. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32872. * The parameter `points` is an array successive Vector3.
  32873. * 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
  32874. * When updating an instance, remember that only point positions can change, not the number of points.
  32875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32876. */
  32877. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32878. if (scene === void 0) { scene = null; }
  32879. if (updatable === void 0) { updatable = false; }
  32880. if (instance === void 0) { instance = null; }
  32881. var options = {
  32882. points: points,
  32883. updatable: updatable,
  32884. instance: instance
  32885. };
  32886. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32887. };
  32888. /**
  32889. * Creates a dashed line mesh.
  32890. * Please consider using the same method from the MeshBuilder class instead.
  32891. * 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.
  32892. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32893. * The parameter `points` is an array successive Vector3.
  32894. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32895. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32896. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32897. * 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
  32898. * When updating an instance, remember that only point positions can change, not the number of points.
  32899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32900. */
  32901. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32902. if (scene === void 0) { scene = null; }
  32903. var options = {
  32904. points: points,
  32905. dashSize: dashSize,
  32906. gapSize: gapSize,
  32907. dashNb: dashNb,
  32908. updatable: updatable,
  32909. instance: instance
  32910. };
  32911. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32912. };
  32913. /**
  32914. * Creates a polygon mesh.
  32915. * Please consider using the same method from the MeshBuilder class instead.
  32916. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32917. * 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.
  32918. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32920. * Remember you can only change the shape positions, not their number when updating a polygon.
  32921. */
  32922. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32923. var options = {
  32924. shape: shape,
  32925. holes: holes,
  32926. updatable: updatable,
  32927. sideOrientation: sideOrientation
  32928. };
  32929. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32930. };
  32931. /**
  32932. * Creates an extruded polygon mesh, with depth in the Y direction.
  32933. * Please consider using the same method from the MeshBuilder class instead.
  32934. */
  32935. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32936. var options = {
  32937. shape: shape,
  32938. holes: holes,
  32939. depth: depth,
  32940. updatable: updatable,
  32941. sideOrientation: sideOrientation
  32942. };
  32943. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32944. };
  32945. /**
  32946. * Creates an extruded shape mesh.
  32947. * 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.
  32948. * Please consider using the same method from the MeshBuilder class instead.
  32949. *
  32950. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32951. * 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
  32952. * extruded along the Z axis.
  32953. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32954. * 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.
  32955. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32956. * 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
  32957. * 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
  32958. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32962. */
  32963. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32964. if (scene === void 0) { scene = null; }
  32965. var options = {
  32966. shape: shape,
  32967. path: path,
  32968. scale: scale,
  32969. rotation: rotation,
  32970. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32971. sideOrientation: sideOrientation,
  32972. instance: instance,
  32973. updatable: updatable
  32974. };
  32975. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32976. };
  32977. /**
  32978. * Creates an custom extruded shape mesh.
  32979. * 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.
  32980. * Please consider using the same method from the MeshBuilder class instead.
  32981. *
  32982. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32983. * 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
  32984. * extruded along the Z axis.
  32985. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32986. * 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
  32987. * and the distance of this point from the begining of the path :
  32988. * ```javascript
  32989. * var rotationFunction = function(i, distance) {
  32990. * // do things
  32991. * return rotationValue; }
  32992. * ```
  32993. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32994. * 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
  32995. * and the distance of this point from the begining of the path :
  32996. * ```javascript
  32997. * var scaleFunction = function(i, distance) {
  32998. * // do things
  32999. * return scaleValue;}
  33000. * ```
  33001. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33002. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33003. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33004. * 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
  33005. * 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
  33006. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33010. */
  33011. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33012. var options = {
  33013. shape: shape,
  33014. path: path,
  33015. scaleFunction: scaleFunction,
  33016. rotationFunction: rotationFunction,
  33017. ribbonCloseArray: ribbonCloseArray,
  33018. ribbonClosePath: ribbonClosePath,
  33019. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33020. sideOrientation: sideOrientation,
  33021. instance: instance,
  33022. updatable: updatable
  33023. };
  33024. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33025. };
  33026. /**
  33027. * Creates lathe mesh.
  33028. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33029. * Please consider using the same method from the MeshBuilder class instead.
  33030. * 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
  33031. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33032. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33033. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33037. */
  33038. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33039. var options = {
  33040. shape: shape,
  33041. radius: radius,
  33042. tessellation: tessellation,
  33043. sideOrientation: sideOrientation,
  33044. updatable: updatable
  33045. };
  33046. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33047. };
  33048. /**
  33049. * Creates a plane mesh.
  33050. * Please consider using the same method from the MeshBuilder class instead.
  33051. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33055. */
  33056. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33057. var options = {
  33058. size: size,
  33059. width: size,
  33060. height: size,
  33061. sideOrientation: sideOrientation,
  33062. updatable: updatable
  33063. };
  33064. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33065. };
  33066. /**
  33067. * Creates a ground mesh.
  33068. * Please consider using the same method from the MeshBuilder class instead.
  33069. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33070. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33072. */
  33073. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33074. var options = {
  33075. width: width,
  33076. height: height,
  33077. subdivisions: subdivisions,
  33078. updatable: updatable
  33079. };
  33080. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33081. };
  33082. /**
  33083. * Creates a tiled ground mesh.
  33084. * Please consider using the same method from the MeshBuilder class instead.
  33085. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33086. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33087. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33088. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33089. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33090. * numbers of subdivisions on the ground width and height of each tile.
  33091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33092. */
  33093. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33094. var options = {
  33095. xmin: xmin,
  33096. zmin: zmin,
  33097. xmax: xmax,
  33098. zmax: zmax,
  33099. subdivisions: subdivisions,
  33100. precision: precision,
  33101. updatable: updatable
  33102. };
  33103. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33104. };
  33105. /**
  33106. * Creates a ground mesh from a height map.
  33107. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33108. * Please consider using the same method from the MeshBuilder class instead.
  33109. * The parameter `url` sets the URL of the height map image resource.
  33110. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33111. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33112. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33113. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33114. * 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).
  33115. * This function is passed the newly built mesh :
  33116. * ```javascript
  33117. * function(mesh) { // do things
  33118. * return; }
  33119. * ```
  33120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33121. */
  33122. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33123. var options = {
  33124. width: width,
  33125. height: height,
  33126. subdivisions: subdivisions,
  33127. minHeight: minHeight,
  33128. maxHeight: maxHeight,
  33129. updatable: updatable,
  33130. onReady: onReady
  33131. };
  33132. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33133. };
  33134. /**
  33135. * Creates a tube mesh.
  33136. * 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.
  33137. * Please consider using the same method from the MeshBuilder class instead.
  33138. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33139. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33140. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33141. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33142. * 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.
  33143. * It must return a radius value (positive float) :
  33144. * ```javascript
  33145. * var radiusFunction = function(i, distance) {
  33146. * // do things
  33147. * return radius; }
  33148. * ```
  33149. * 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
  33150. * 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
  33151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33154. */
  33155. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33156. var options = {
  33157. path: path,
  33158. radius: radius,
  33159. tessellation: tessellation,
  33160. radiusFunction: radiusFunction,
  33161. arc: 1,
  33162. cap: cap,
  33163. updatable: updatable,
  33164. sideOrientation: sideOrientation,
  33165. instance: instance
  33166. };
  33167. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33168. };
  33169. /**
  33170. * Creates a polyhedron mesh.
  33171. * Please consider using the same method from the MeshBuilder class instead.
  33172. * 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
  33173. * to choose the wanted type.
  33174. * The parameter `size` (positive float, default 1) sets the polygon size.
  33175. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33176. * 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`.
  33177. * 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
  33178. * 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)`).
  33179. * 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
  33180. * 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.
  33181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33184. */
  33185. Mesh.CreatePolyhedron = function (name, options, scene) {
  33186. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33187. };
  33188. /**
  33189. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33190. * Please consider using the same method from the MeshBuilder class instead.
  33191. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33192. * 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`).
  33193. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33194. * 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.
  33195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33198. */
  33199. Mesh.CreateIcoSphere = function (name, options, scene) {
  33200. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33201. };
  33202. /**
  33203. * Creates a decal mesh.
  33204. * Please consider using the same method from the MeshBuilder class instead.
  33205. * 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.
  33206. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33207. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33208. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33209. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33210. */
  33211. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33212. var options = {
  33213. position: position,
  33214. normal: normal,
  33215. size: size,
  33216. angle: angle
  33217. };
  33218. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33219. };
  33220. // Skeletons
  33221. /**
  33222. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33223. */
  33224. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33225. if (!this._sourcePositions) {
  33226. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33227. if (!source) {
  33228. return this._sourcePositions;
  33229. }
  33230. this._sourcePositions = new Float32Array(source);
  33231. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33232. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33233. }
  33234. }
  33235. return this._sourcePositions;
  33236. };
  33237. /**
  33238. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33239. */
  33240. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33241. if (!this._sourceNormals) {
  33242. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33243. if (!source) {
  33244. return this._sourceNormals;
  33245. }
  33246. this._sourceNormals = new Float32Array(source);
  33247. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33248. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33249. }
  33250. }
  33251. return this._sourceNormals;
  33252. };
  33253. /**
  33254. * Updates the vertex buffer by applying transformation from the bones.
  33255. * Returns the Mesh.
  33256. *
  33257. * @param {skeleton} skeleton to apply
  33258. */
  33259. Mesh.prototype.applySkeleton = function (skeleton) {
  33260. if (!this.geometry) {
  33261. return this;
  33262. }
  33263. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33264. return this;
  33265. }
  33266. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33268. return this;
  33269. }
  33270. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33271. return this;
  33272. }
  33273. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33274. return this;
  33275. }
  33276. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33277. return this;
  33278. }
  33279. if (!this._sourcePositions) {
  33280. var submeshes = this.subMeshes.slice();
  33281. this.setPositionsForCPUSkinning();
  33282. this.subMeshes = submeshes;
  33283. }
  33284. if (!this._sourceNormals) {
  33285. this.setNormalsForCPUSkinning();
  33286. }
  33287. // positionsData checks for not being Float32Array will only pass at most once
  33288. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33289. if (!positionsData) {
  33290. return this;
  33291. }
  33292. if (!(positionsData instanceof Float32Array)) {
  33293. positionsData = new Float32Array(positionsData);
  33294. }
  33295. // normalsData checks for not being Float32Array will only pass at most once
  33296. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33297. if (!normalsData) {
  33298. return this;
  33299. }
  33300. if (!(normalsData instanceof Float32Array)) {
  33301. normalsData = new Float32Array(normalsData);
  33302. }
  33303. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33304. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33305. if (!matricesWeightsData || !matricesIndicesData) {
  33306. return this;
  33307. }
  33308. var needExtras = this.numBoneInfluencers > 4;
  33309. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33310. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33311. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33312. var tempVector3 = BABYLON.Vector3.Zero();
  33313. var finalMatrix = new BABYLON.Matrix();
  33314. var tempMatrix = new BABYLON.Matrix();
  33315. var matWeightIdx = 0;
  33316. var inf;
  33317. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33318. var weight;
  33319. for (inf = 0; inf < 4; inf++) {
  33320. weight = matricesWeightsData[matWeightIdx + inf];
  33321. if (weight > 0) {
  33322. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33323. finalMatrix.addToSelf(tempMatrix);
  33324. }
  33325. else
  33326. break;
  33327. }
  33328. if (needExtras) {
  33329. for (inf = 0; inf < 4; inf++) {
  33330. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33331. if (weight > 0) {
  33332. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33333. finalMatrix.addToSelf(tempMatrix);
  33334. }
  33335. else
  33336. break;
  33337. }
  33338. }
  33339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33340. tempVector3.toArray(positionsData, index);
  33341. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33342. tempVector3.toArray(normalsData, index);
  33343. finalMatrix.reset();
  33344. }
  33345. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33346. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33347. return this;
  33348. };
  33349. // Tools
  33350. /**
  33351. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33352. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33353. */
  33354. Mesh.MinMax = function (meshes) {
  33355. var minVector = null;
  33356. var maxVector = null;
  33357. meshes.forEach(function (mesh, index, array) {
  33358. var boundingInfo = mesh.getBoundingInfo();
  33359. var boundingBox = boundingInfo.boundingBox;
  33360. if (!minVector || !maxVector) {
  33361. minVector = boundingBox.minimumWorld;
  33362. maxVector = boundingBox.maximumWorld;
  33363. }
  33364. else {
  33365. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33366. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33367. }
  33368. });
  33369. if (!minVector || !maxVector) {
  33370. return {
  33371. min: BABYLON.Vector3.Zero(),
  33372. max: BABYLON.Vector3.Zero()
  33373. };
  33374. }
  33375. return {
  33376. min: minVector,
  33377. max: maxVector
  33378. };
  33379. };
  33380. /**
  33381. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33382. */
  33383. Mesh.Center = function (meshesOrMinMaxVector) {
  33384. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33385. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33386. };
  33387. /**
  33388. * Merge the array of meshes into a single mesh for performance reasons.
  33389. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33390. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33391. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33392. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33393. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33394. */
  33395. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33396. if (disposeSource === void 0) { disposeSource = true; }
  33397. var index;
  33398. if (!allow32BitsIndices) {
  33399. var totalVertices = 0;
  33400. // Counting vertices
  33401. for (index = 0; index < meshes.length; index++) {
  33402. if (meshes[index]) {
  33403. totalVertices += meshes[index].getTotalVertices();
  33404. if (totalVertices > 65536) {
  33405. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33406. return null;
  33407. }
  33408. }
  33409. }
  33410. }
  33411. // Merge
  33412. var vertexData = null;
  33413. var otherVertexData;
  33414. var indiceArray = new Array();
  33415. var source = null;
  33416. for (index = 0; index < meshes.length; index++) {
  33417. if (meshes[index]) {
  33418. meshes[index].computeWorldMatrix(true);
  33419. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33420. otherVertexData.transform(meshes[index].getWorldMatrix());
  33421. if (vertexData) {
  33422. vertexData.merge(otherVertexData);
  33423. }
  33424. else {
  33425. vertexData = otherVertexData;
  33426. source = meshes[index];
  33427. }
  33428. if (subdivideWithSubMeshes) {
  33429. indiceArray.push(meshes[index].getTotalIndices());
  33430. }
  33431. }
  33432. }
  33433. source = source;
  33434. if (!meshSubclass) {
  33435. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33436. }
  33437. vertexData.applyToMesh(meshSubclass);
  33438. // Setting properties
  33439. meshSubclass.material = source.material;
  33440. meshSubclass.checkCollisions = source.checkCollisions;
  33441. // Cleaning
  33442. if (disposeSource) {
  33443. for (index = 0; index < meshes.length; index++) {
  33444. if (meshes[index]) {
  33445. meshes[index].dispose();
  33446. }
  33447. }
  33448. }
  33449. // Subdivide
  33450. if (subdivideWithSubMeshes) {
  33451. //-- Suppresions du submesh global
  33452. meshSubclass.releaseSubMeshes();
  33453. index = 0;
  33454. var offset = 0;
  33455. //-- aplique la subdivision en fonction du tableau d'indices
  33456. while (index < indiceArray.length) {
  33457. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33458. offset += indiceArray[index];
  33459. index++;
  33460. }
  33461. }
  33462. return meshSubclass;
  33463. };
  33464. // Consts
  33465. Mesh._FRONTSIDE = 0;
  33466. Mesh._BACKSIDE = 1;
  33467. Mesh._DOUBLESIDE = 2;
  33468. Mesh._DEFAULTSIDE = 0;
  33469. Mesh._NO_CAP = 0;
  33470. Mesh._CAP_START = 1;
  33471. Mesh._CAP_END = 2;
  33472. Mesh._CAP_ALL = 3;
  33473. return Mesh;
  33474. }(BABYLON.AbstractMesh));
  33475. BABYLON.Mesh = Mesh;
  33476. })(BABYLON || (BABYLON = {}));
  33477. //# sourceMappingURL=babylon.mesh.js.map
  33478. var BABYLON;
  33479. (function (BABYLON) {
  33480. var BaseSubMesh = /** @class */ (function () {
  33481. function BaseSubMesh() {
  33482. }
  33483. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33484. get: function () {
  33485. return this._materialEffect;
  33486. },
  33487. enumerable: true,
  33488. configurable: true
  33489. });
  33490. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33491. if (defines === void 0) { defines = null; }
  33492. if (this._materialEffect === effect) {
  33493. if (!effect) {
  33494. this._materialDefines = null;
  33495. }
  33496. return;
  33497. }
  33498. this._materialDefines = defines;
  33499. this._materialEffect = effect;
  33500. };
  33501. return BaseSubMesh;
  33502. }());
  33503. BABYLON.BaseSubMesh = BaseSubMesh;
  33504. var SubMesh = /** @class */ (function (_super) {
  33505. __extends(SubMesh, _super);
  33506. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33507. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33508. var _this = _super.call(this) || this;
  33509. _this.materialIndex = materialIndex;
  33510. _this.verticesStart = verticesStart;
  33511. _this.verticesCount = verticesCount;
  33512. _this.indexStart = indexStart;
  33513. _this.indexCount = indexCount;
  33514. _this._renderId = 0;
  33515. _this._mesh = mesh;
  33516. _this._renderingMesh = renderingMesh || mesh;
  33517. mesh.subMeshes.push(_this);
  33518. _this._trianglePlanes = [];
  33519. _this._id = mesh.subMeshes.length - 1;
  33520. if (createBoundingBox) {
  33521. _this.refreshBoundingInfo();
  33522. mesh.computeWorldMatrix(true);
  33523. }
  33524. return _this;
  33525. }
  33526. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33527. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33528. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33529. };
  33530. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33531. get: function () {
  33532. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33533. },
  33534. enumerable: true,
  33535. configurable: true
  33536. });
  33537. /**
  33538. * Returns the submesh BoudingInfo object.
  33539. */
  33540. SubMesh.prototype.getBoundingInfo = function () {
  33541. if (this.IsGlobal) {
  33542. return this._mesh.getBoundingInfo();
  33543. }
  33544. return this._boundingInfo;
  33545. };
  33546. /**
  33547. * Sets the submesh BoundingInfo.
  33548. * Return the SubMesh.
  33549. */
  33550. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33551. this._boundingInfo = boundingInfo;
  33552. return this;
  33553. };
  33554. /**
  33555. * Returns the mesh of the current submesh.
  33556. */
  33557. SubMesh.prototype.getMesh = function () {
  33558. return this._mesh;
  33559. };
  33560. /**
  33561. * Returns the rendering mesh of the submesh.
  33562. */
  33563. SubMesh.prototype.getRenderingMesh = function () {
  33564. return this._renderingMesh;
  33565. };
  33566. /**
  33567. * Returns the submesh material.
  33568. */
  33569. SubMesh.prototype.getMaterial = function () {
  33570. var rootMaterial = this._renderingMesh.material;
  33571. if (rootMaterial === null || rootMaterial === undefined) {
  33572. return this._mesh.getScene().defaultMaterial;
  33573. }
  33574. else if (rootMaterial.getSubMaterial) {
  33575. var multiMaterial = rootMaterial;
  33576. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33577. if (this._currentMaterial !== effectiveMaterial) {
  33578. this._currentMaterial = effectiveMaterial;
  33579. this._materialDefines = null;
  33580. }
  33581. return effectiveMaterial;
  33582. }
  33583. return rootMaterial;
  33584. };
  33585. // Methods
  33586. /**
  33587. * Sets a new updated BoundingInfo object to the submesh.
  33588. * Returns the SubMesh.
  33589. */
  33590. SubMesh.prototype.refreshBoundingInfo = function () {
  33591. this._lastColliderWorldVertices = null;
  33592. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33593. return this;
  33594. }
  33595. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33596. if (!data) {
  33597. this._boundingInfo = this._mesh.getBoundingInfo();
  33598. return this;
  33599. }
  33600. var indices = this._renderingMesh.getIndices();
  33601. var extend;
  33602. //is this the only submesh?
  33603. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33604. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33605. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33606. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33607. }
  33608. else {
  33609. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33610. }
  33611. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33612. return this;
  33613. };
  33614. SubMesh.prototype._checkCollision = function (collider) {
  33615. var boundingInfo = this.getBoundingInfo();
  33616. return boundingInfo._checkCollision(collider);
  33617. };
  33618. /**
  33619. * Updates the submesh BoundingInfo.
  33620. * Returns the Submesh.
  33621. */
  33622. SubMesh.prototype.updateBoundingInfo = function (world) {
  33623. var boundingInfo = this.getBoundingInfo();
  33624. if (!boundingInfo) {
  33625. this.refreshBoundingInfo();
  33626. boundingInfo = this.getBoundingInfo();
  33627. }
  33628. boundingInfo.update(world);
  33629. return this;
  33630. };
  33631. /**
  33632. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33633. * Boolean returned.
  33634. */
  33635. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33636. var boundingInfo = this.getBoundingInfo();
  33637. if (!boundingInfo) {
  33638. return false;
  33639. }
  33640. return boundingInfo.isInFrustum(frustumPlanes);
  33641. };
  33642. /**
  33643. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33644. * Boolean returned.
  33645. */
  33646. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33647. var boundingInfo = this.getBoundingInfo();
  33648. if (!boundingInfo) {
  33649. return false;
  33650. }
  33651. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33652. };
  33653. /**
  33654. * Renders the submesh.
  33655. * Returns it.
  33656. */
  33657. SubMesh.prototype.render = function (enableAlphaMode) {
  33658. this._renderingMesh.render(this, enableAlphaMode);
  33659. return this;
  33660. };
  33661. /**
  33662. * Returns a new Index Buffer.
  33663. * Type returned : WebGLBuffer.
  33664. */
  33665. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33666. if (!this._linesIndexBuffer) {
  33667. var linesIndices = [];
  33668. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33669. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33670. }
  33671. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33672. this.linesIndexCount = linesIndices.length;
  33673. }
  33674. return this._linesIndexBuffer;
  33675. };
  33676. /**
  33677. * True is the passed Ray intersects the submesh bounding box.
  33678. * Boolean returned.
  33679. */
  33680. SubMesh.prototype.canIntersects = function (ray) {
  33681. var boundingInfo = this.getBoundingInfo();
  33682. if (!boundingInfo) {
  33683. return false;
  33684. }
  33685. return ray.intersectsBox(boundingInfo.boundingBox);
  33686. };
  33687. /**
  33688. * Returns an object IntersectionInfo.
  33689. */
  33690. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33691. var intersectInfo = null;
  33692. var material = this.getMaterial();
  33693. if (!material) {
  33694. return null;
  33695. }
  33696. switch (material.fillMode) {
  33697. case BABYLON.Material.PointListDrawMode:
  33698. case BABYLON.Material.LineListDrawMode:
  33699. case BABYLON.Material.LineLoopDrawMode:
  33700. case BABYLON.Material.LineStripDrawMode:
  33701. case BABYLON.Material.TriangleFanDrawMode:
  33702. case BABYLON.Material.TriangleStripDrawMode:
  33703. return null;
  33704. }
  33705. // LineMesh first as it's also a Mesh...
  33706. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33707. var lineMesh = this._mesh;
  33708. // Line test
  33709. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33710. var p0 = positions[indices[index]];
  33711. var p1 = positions[indices[index + 1]];
  33712. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33713. if (length < 0) {
  33714. continue;
  33715. }
  33716. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33717. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33718. if (fastCheck) {
  33719. break;
  33720. }
  33721. }
  33722. }
  33723. }
  33724. else {
  33725. // Triangles test
  33726. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33727. var p0 = positions[indices[index]];
  33728. var p1 = positions[indices[index + 1]];
  33729. var p2 = positions[indices[index + 2]];
  33730. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33731. if (currentIntersectInfo) {
  33732. if (currentIntersectInfo.distance < 0) {
  33733. continue;
  33734. }
  33735. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33736. intersectInfo = currentIntersectInfo;
  33737. intersectInfo.faceId = index / 3;
  33738. if (fastCheck) {
  33739. break;
  33740. }
  33741. }
  33742. }
  33743. }
  33744. }
  33745. return intersectInfo;
  33746. };
  33747. SubMesh.prototype._rebuild = function () {
  33748. if (this._linesIndexBuffer) {
  33749. this._linesIndexBuffer = null;
  33750. }
  33751. };
  33752. // Clone
  33753. /**
  33754. * Creates a new Submesh from the passed Mesh.
  33755. */
  33756. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33757. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33758. if (!this.IsGlobal) {
  33759. var boundingInfo = this.getBoundingInfo();
  33760. if (!boundingInfo) {
  33761. return result;
  33762. }
  33763. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33764. }
  33765. return result;
  33766. };
  33767. // Dispose
  33768. /**
  33769. * Disposes the Submesh.
  33770. * Returns nothing.
  33771. */
  33772. SubMesh.prototype.dispose = function () {
  33773. if (this._linesIndexBuffer) {
  33774. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33775. this._linesIndexBuffer = null;
  33776. }
  33777. // Remove from mesh
  33778. var index = this._mesh.subMeshes.indexOf(this);
  33779. this._mesh.subMeshes.splice(index, 1);
  33780. };
  33781. // Statics
  33782. /**
  33783. * Creates a new Submesh from the passed parameters :
  33784. * - materialIndex (integer) : the index of the main mesh material.
  33785. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33786. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33787. * - mesh (Mesh) : the main mesh to create the submesh from.
  33788. * - renderingMesh (optional Mesh) : rendering mesh.
  33789. */
  33790. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33791. var minVertexIndex = Number.MAX_VALUE;
  33792. var maxVertexIndex = -Number.MAX_VALUE;
  33793. renderingMesh = (renderingMesh || mesh);
  33794. var indices = renderingMesh.getIndices();
  33795. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33796. var vertexIndex = indices[index];
  33797. if (vertexIndex < minVertexIndex)
  33798. minVertexIndex = vertexIndex;
  33799. if (vertexIndex > maxVertexIndex)
  33800. maxVertexIndex = vertexIndex;
  33801. }
  33802. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33803. };
  33804. return SubMesh;
  33805. }(BaseSubMesh));
  33806. BABYLON.SubMesh = SubMesh;
  33807. })(BABYLON || (BABYLON = {}));
  33808. //# sourceMappingURL=babylon.subMesh.js.map
  33809. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33810. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33811. s = arguments[i];
  33812. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33813. t[p] = s[p];
  33814. }
  33815. return t;
  33816. };
  33817. var BABYLON;
  33818. (function (BABYLON) {
  33819. /**
  33820. * Manages the defines for the Material
  33821. */
  33822. var MaterialDefines = /** @class */ (function () {
  33823. function MaterialDefines() {
  33824. this._isDirty = true;
  33825. /** @ignore */
  33826. this._areLightsDirty = true;
  33827. /** @ignore */
  33828. this._areAttributesDirty = true;
  33829. /** @ignore */
  33830. this._areTexturesDirty = true;
  33831. /** @ignore */
  33832. this._areFresnelDirty = true;
  33833. /** @ignore */
  33834. this._areMiscDirty = true;
  33835. /** @ignore */
  33836. this._areImageProcessingDirty = true;
  33837. /** @ignore */
  33838. this._normals = false;
  33839. /** @ignore */
  33840. this._uvs = false;
  33841. /** @ignore */
  33842. this._needNormals = false;
  33843. /** @ignore */
  33844. this._needUVs = false;
  33845. }
  33846. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33847. /**
  33848. * Specifies if the material needs to be re-calculated
  33849. */
  33850. get: function () {
  33851. return this._isDirty;
  33852. },
  33853. enumerable: true,
  33854. configurable: true
  33855. });
  33856. /**
  33857. * Marks the material to indicate that it has been re-calculated
  33858. */
  33859. MaterialDefines.prototype.markAsProcessed = function () {
  33860. this._isDirty = false;
  33861. this._areAttributesDirty = false;
  33862. this._areTexturesDirty = false;
  33863. this._areFresnelDirty = false;
  33864. this._areLightsDirty = false;
  33865. this._areMiscDirty = false;
  33866. this._areImageProcessingDirty = false;
  33867. };
  33868. /**
  33869. * Marks the material to indicate that it needs to be re-calculated
  33870. */
  33871. MaterialDefines.prototype.markAsUnprocessed = function () {
  33872. this._isDirty = true;
  33873. };
  33874. /**
  33875. * Marks the material to indicate all of its defines need to be re-calculated
  33876. */
  33877. MaterialDefines.prototype.markAllAsDirty = function () {
  33878. this._areTexturesDirty = true;
  33879. this._areAttributesDirty = true;
  33880. this._areLightsDirty = true;
  33881. this._areFresnelDirty = true;
  33882. this._areMiscDirty = true;
  33883. this._areImageProcessingDirty = true;
  33884. this._isDirty = true;
  33885. };
  33886. /**
  33887. * Marks the material to indicate that image processing needs to be re-calculated
  33888. */
  33889. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33890. this._areImageProcessingDirty = true;
  33891. this._isDirty = true;
  33892. };
  33893. /**
  33894. * Marks the material to indicate the lights need to be re-calculated
  33895. */
  33896. MaterialDefines.prototype.markAsLightDirty = function () {
  33897. this._areLightsDirty = true;
  33898. this._isDirty = true;
  33899. };
  33900. /**
  33901. * Marks the attribute state as changed
  33902. */
  33903. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33904. this._areAttributesDirty = true;
  33905. this._isDirty = true;
  33906. };
  33907. /**
  33908. * Marks the texture state as changed
  33909. */
  33910. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33911. this._areTexturesDirty = true;
  33912. this._isDirty = true;
  33913. };
  33914. /**
  33915. * Marks the fresnel state as changed
  33916. */
  33917. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33918. this._areFresnelDirty = true;
  33919. this._isDirty = true;
  33920. };
  33921. /**
  33922. * Marks the misc state as changed
  33923. */
  33924. MaterialDefines.prototype.markAsMiscDirty = function () {
  33925. this._areMiscDirty = true;
  33926. this._isDirty = true;
  33927. };
  33928. /**
  33929. * Rebuilds the material defines
  33930. */
  33931. MaterialDefines.prototype.rebuild = function () {
  33932. if (this._keys) {
  33933. delete this._keys;
  33934. }
  33935. this._keys = [];
  33936. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33937. var key = _a[_i];
  33938. if (key[0] === "_") {
  33939. continue;
  33940. }
  33941. this._keys.push(key);
  33942. }
  33943. };
  33944. /**
  33945. * Specifies if two material defines are equal
  33946. * @param other - A material define instance to compare to
  33947. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33948. */
  33949. MaterialDefines.prototype.isEqual = function (other) {
  33950. if (this._keys.length !== other._keys.length) {
  33951. return false;
  33952. }
  33953. for (var index = 0; index < this._keys.length; index++) {
  33954. var prop = this._keys[index];
  33955. if (this[prop] !== other[prop]) {
  33956. return false;
  33957. }
  33958. }
  33959. return true;
  33960. };
  33961. /**
  33962. * Clones this instance's defines to another instance
  33963. * @param other - material defines to clone values to
  33964. */
  33965. MaterialDefines.prototype.cloneTo = function (other) {
  33966. if (this._keys.length !== other._keys.length) {
  33967. other._keys = this._keys.slice(0);
  33968. }
  33969. for (var index = 0; index < this._keys.length; index++) {
  33970. var prop = this._keys[index];
  33971. other[prop] = this[prop];
  33972. }
  33973. };
  33974. /**
  33975. * Resets the material define values
  33976. */
  33977. MaterialDefines.prototype.reset = function () {
  33978. for (var index = 0; index < this._keys.length; index++) {
  33979. var prop = this._keys[index];
  33980. var type = typeof this[prop];
  33981. switch (type) {
  33982. case "number":
  33983. this[prop] = 0;
  33984. break;
  33985. case "string":
  33986. this[prop] = "";
  33987. break;
  33988. default:
  33989. this[prop] = false;
  33990. break;
  33991. }
  33992. }
  33993. };
  33994. /**
  33995. * Converts the material define values to a string
  33996. * @returns - String of material define information
  33997. */
  33998. MaterialDefines.prototype.toString = function () {
  33999. var result = "";
  34000. for (var index = 0; index < this._keys.length; index++) {
  34001. var prop = this._keys[index];
  34002. var value = this[prop];
  34003. var type = typeof value;
  34004. switch (type) {
  34005. case "number":
  34006. case "string":
  34007. result += "#define " + prop + " " + value + "\n";
  34008. break;
  34009. default:
  34010. if (value) {
  34011. result += "#define " + prop + "\n";
  34012. }
  34013. break;
  34014. }
  34015. }
  34016. return result;
  34017. };
  34018. return MaterialDefines;
  34019. }());
  34020. BABYLON.MaterialDefines = MaterialDefines;
  34021. /**
  34022. * Base class for the main features of a material in Babylon.js
  34023. */
  34024. var Material = /** @class */ (function () {
  34025. /**
  34026. * Creates a material instance
  34027. * @param name defines the name of the material
  34028. * @param scene defines the scene to reference
  34029. * @param doNotAdd specifies if the material should be added to the scene
  34030. */
  34031. function Material(name, scene, doNotAdd) {
  34032. /**
  34033. * Specifies if the ready state should be checked on each call
  34034. */
  34035. this.checkReadyOnEveryCall = false;
  34036. /**
  34037. * Specifies if the ready state should be checked once
  34038. */
  34039. this.checkReadyOnlyOnce = false;
  34040. /**
  34041. * The state of the material
  34042. */
  34043. this.state = "";
  34044. /**
  34045. * The alpha value of the material
  34046. */
  34047. this._alpha = 1.0;
  34048. /**
  34049. * Specifies if back face culling is enabled
  34050. */
  34051. this._backFaceCulling = true;
  34052. /**
  34053. * Specifies if the material should be serialized
  34054. */
  34055. this.doNotSerialize = false;
  34056. /**
  34057. * Specifies if the effect should be stored on sub meshes
  34058. */
  34059. this.storeEffectOnSubMeshes = false;
  34060. /**
  34061. * An event triggered when the material is disposed
  34062. */
  34063. this.onDisposeObservable = new BABYLON.Observable();
  34064. /**
  34065. * An event triggered when the material is bound
  34066. */
  34067. this.onBindObservable = new BABYLON.Observable();
  34068. /**
  34069. * An event triggered when the material is unbound
  34070. */
  34071. this.onUnBindObservable = new BABYLON.Observable();
  34072. /**
  34073. * Stores the value of the alpha mode
  34074. */
  34075. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34076. /**
  34077. * Stores the state of the need depth pre-pass value
  34078. */
  34079. this._needDepthPrePass = false;
  34080. /**
  34081. * Specifies if depth writing should be disabled
  34082. */
  34083. this.disableDepthWrite = false;
  34084. /**
  34085. * Specifies if depth writing should be forced
  34086. */
  34087. this.forceDepthWrite = false;
  34088. /**
  34089. * Specifies if there should be a separate pass for culling
  34090. */
  34091. this.separateCullingPass = false;
  34092. /**
  34093. * Stores the state specifing if fog should be enabled
  34094. */
  34095. this._fogEnabled = true;
  34096. /**
  34097. * Stores the size of points
  34098. */
  34099. this.pointSize = 1.0;
  34100. /**
  34101. * Stores the z offset value
  34102. */
  34103. this.zOffset = 0;
  34104. /**
  34105. * Specifies if the material was previously ready
  34106. */
  34107. this._wasPreviouslyReady = false;
  34108. /**
  34109. * Stores the fill mode state
  34110. */
  34111. this._fillMode = Material.TriangleFillMode;
  34112. this.name = name;
  34113. this.id = name || BABYLON.Tools.RandomId();
  34114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34115. if (this._scene.useRightHandedSystem) {
  34116. this.sideOrientation = Material.ClockWiseSideOrientation;
  34117. }
  34118. else {
  34119. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34120. }
  34121. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34122. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34123. if (!doNotAdd) {
  34124. this._scene.materials.push(this);
  34125. }
  34126. }
  34127. Object.defineProperty(Material, "TriangleFillMode", {
  34128. /**
  34129. * Returns the triangle fill mode
  34130. */
  34131. get: function () {
  34132. return Material._TriangleFillMode;
  34133. },
  34134. enumerable: true,
  34135. configurable: true
  34136. });
  34137. Object.defineProperty(Material, "WireFrameFillMode", {
  34138. /**
  34139. * Returns the wireframe mode
  34140. */
  34141. get: function () {
  34142. return Material._WireFrameFillMode;
  34143. },
  34144. enumerable: true,
  34145. configurable: true
  34146. });
  34147. Object.defineProperty(Material, "PointFillMode", {
  34148. /**
  34149. * Returns the point fill mode
  34150. */
  34151. get: function () {
  34152. return Material._PointFillMode;
  34153. },
  34154. enumerable: true,
  34155. configurable: true
  34156. });
  34157. Object.defineProperty(Material, "PointListDrawMode", {
  34158. /**
  34159. * Returns the point list draw mode
  34160. */
  34161. get: function () {
  34162. return Material._PointListDrawMode;
  34163. },
  34164. enumerable: true,
  34165. configurable: true
  34166. });
  34167. Object.defineProperty(Material, "LineListDrawMode", {
  34168. /**
  34169. * Returns the line list draw mode
  34170. */
  34171. get: function () {
  34172. return Material._LineListDrawMode;
  34173. },
  34174. enumerable: true,
  34175. configurable: true
  34176. });
  34177. Object.defineProperty(Material, "LineLoopDrawMode", {
  34178. /**
  34179. * Returns the line loop draw mode
  34180. */
  34181. get: function () {
  34182. return Material._LineLoopDrawMode;
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. Object.defineProperty(Material, "LineStripDrawMode", {
  34188. /**
  34189. * Returns the line strip draw mode
  34190. */
  34191. get: function () {
  34192. return Material._LineStripDrawMode;
  34193. },
  34194. enumerable: true,
  34195. configurable: true
  34196. });
  34197. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34198. /**
  34199. * Returns the triangle strip draw mode
  34200. */
  34201. get: function () {
  34202. return Material._TriangleStripDrawMode;
  34203. },
  34204. enumerable: true,
  34205. configurable: true
  34206. });
  34207. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34208. /**
  34209. * Returns the triangle fan draw mode
  34210. */
  34211. get: function () {
  34212. return Material._TriangleFanDrawMode;
  34213. },
  34214. enumerable: true,
  34215. configurable: true
  34216. });
  34217. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34218. /**
  34219. * Returns the clock-wise side orientation
  34220. */
  34221. get: function () {
  34222. return Material._ClockWiseSideOrientation;
  34223. },
  34224. enumerable: true,
  34225. configurable: true
  34226. });
  34227. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34228. /**
  34229. * Returns the counter clock-wise side orientation
  34230. */
  34231. get: function () {
  34232. return Material._CounterClockWiseSideOrientation;
  34233. },
  34234. enumerable: true,
  34235. configurable: true
  34236. });
  34237. Object.defineProperty(Material, "TextureDirtyFlag", {
  34238. /**
  34239. * Returns the dirty texture flag value
  34240. */
  34241. get: function () {
  34242. return Material._TextureDirtyFlag;
  34243. },
  34244. enumerable: true,
  34245. configurable: true
  34246. });
  34247. Object.defineProperty(Material, "LightDirtyFlag", {
  34248. /**
  34249. * Returns the dirty light flag value
  34250. */
  34251. get: function () {
  34252. return Material._LightDirtyFlag;
  34253. },
  34254. enumerable: true,
  34255. configurable: true
  34256. });
  34257. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34258. /**
  34259. * Returns the dirty fresnel flag value
  34260. */
  34261. get: function () {
  34262. return Material._FresnelDirtyFlag;
  34263. },
  34264. enumerable: true,
  34265. configurable: true
  34266. });
  34267. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34268. /**
  34269. * Returns the dirty attributes flag value
  34270. */
  34271. get: function () {
  34272. return Material._AttributesDirtyFlag;
  34273. },
  34274. enumerable: true,
  34275. configurable: true
  34276. });
  34277. Object.defineProperty(Material, "MiscDirtyFlag", {
  34278. /**
  34279. * Returns the dirty misc flag value
  34280. */
  34281. get: function () {
  34282. return Material._MiscDirtyFlag;
  34283. },
  34284. enumerable: true,
  34285. configurable: true
  34286. });
  34287. Object.defineProperty(Material.prototype, "alpha", {
  34288. /**
  34289. * Gets the alpha value of the material
  34290. */
  34291. get: function () {
  34292. return this._alpha;
  34293. },
  34294. /**
  34295. * Sets the alpha value of the material
  34296. */
  34297. set: function (value) {
  34298. if (this._alpha === value) {
  34299. return;
  34300. }
  34301. this._alpha = value;
  34302. this.markAsDirty(Material.MiscDirtyFlag);
  34303. },
  34304. enumerable: true,
  34305. configurable: true
  34306. });
  34307. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34308. /**
  34309. * Gets the back-face culling state
  34310. */
  34311. get: function () {
  34312. return this._backFaceCulling;
  34313. },
  34314. /**
  34315. * Sets the back-face culling state
  34316. */
  34317. set: function (value) {
  34318. if (this._backFaceCulling === value) {
  34319. return;
  34320. }
  34321. this._backFaceCulling = value;
  34322. this.markAsDirty(Material.TextureDirtyFlag);
  34323. },
  34324. enumerable: true,
  34325. configurable: true
  34326. });
  34327. Object.defineProperty(Material.prototype, "onDispose", {
  34328. /**
  34329. * Called during a dispose event
  34330. */
  34331. set: function (callback) {
  34332. if (this._onDisposeObserver) {
  34333. this.onDisposeObservable.remove(this._onDisposeObserver);
  34334. }
  34335. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. Object.defineProperty(Material.prototype, "onBind", {
  34341. /**
  34342. * Called during a bind event
  34343. */
  34344. set: function (callback) {
  34345. if (this._onBindObserver) {
  34346. this.onBindObservable.remove(this._onBindObserver);
  34347. }
  34348. this._onBindObserver = this.onBindObservable.add(callback);
  34349. },
  34350. enumerable: true,
  34351. configurable: true
  34352. });
  34353. Object.defineProperty(Material.prototype, "alphaMode", {
  34354. /**
  34355. * Gets the value of the alpha mode
  34356. */
  34357. get: function () {
  34358. return this._alphaMode;
  34359. },
  34360. /**
  34361. * Sets the value of the alpha mode.
  34362. *
  34363. * | Value | Type | Description |
  34364. * | --- | --- | --- |
  34365. * | 0 | ALPHA_DISABLE | |
  34366. * | 1 | ALPHA_ADD | |
  34367. * | 2 | ALPHA_COMBINE | |
  34368. * | 3 | ALPHA_SUBTRACT | |
  34369. * | 4 | ALPHA_MULTIPLY | |
  34370. * | 5 | ALPHA_MAXIMIZED | |
  34371. * | 6 | ALPHA_ONEONE | |
  34372. * | 7 | ALPHA_PREMULTIPLIED | |
  34373. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34374. * | 9 | ALPHA_INTERPOLATE | |
  34375. * | 10 | ALPHA_SCREENMODE | |
  34376. *
  34377. */
  34378. set: function (value) {
  34379. if (this._alphaMode === value) {
  34380. return;
  34381. }
  34382. this._alphaMode = value;
  34383. this.markAsDirty(Material.TextureDirtyFlag);
  34384. },
  34385. enumerable: true,
  34386. configurable: true
  34387. });
  34388. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34389. /**
  34390. * Gets the depth pre-pass value
  34391. */
  34392. get: function () {
  34393. return this._needDepthPrePass;
  34394. },
  34395. /**
  34396. * Sets the need depth pre-pass value
  34397. */
  34398. set: function (value) {
  34399. if (this._needDepthPrePass === value) {
  34400. return;
  34401. }
  34402. this._needDepthPrePass = value;
  34403. if (this._needDepthPrePass) {
  34404. this.checkReadyOnEveryCall = true;
  34405. }
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(Material.prototype, "fogEnabled", {
  34411. /**
  34412. * Gets the value of the fog enabled state
  34413. */
  34414. get: function () {
  34415. return this._fogEnabled;
  34416. },
  34417. /**
  34418. * Sets the state for enabling fog
  34419. */
  34420. set: function (value) {
  34421. if (this._fogEnabled === value) {
  34422. return;
  34423. }
  34424. this._fogEnabled = value;
  34425. this.markAsDirty(Material.MiscDirtyFlag);
  34426. },
  34427. enumerable: true,
  34428. configurable: true
  34429. });
  34430. Object.defineProperty(Material.prototype, "wireframe", {
  34431. /**
  34432. * Gets a value specifying if wireframe mode is enabled
  34433. */
  34434. get: function () {
  34435. switch (this._fillMode) {
  34436. case Material.WireFrameFillMode:
  34437. case Material.LineListDrawMode:
  34438. case Material.LineLoopDrawMode:
  34439. case Material.LineStripDrawMode:
  34440. return true;
  34441. }
  34442. return this._scene.forceWireframe;
  34443. },
  34444. /**
  34445. * Sets the state of wireframe mode
  34446. */
  34447. set: function (value) {
  34448. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34449. },
  34450. enumerable: true,
  34451. configurable: true
  34452. });
  34453. Object.defineProperty(Material.prototype, "pointsCloud", {
  34454. /**
  34455. * Gets the value specifying if point clouds are enabled
  34456. */
  34457. get: function () {
  34458. switch (this._fillMode) {
  34459. case Material.PointFillMode:
  34460. case Material.PointListDrawMode:
  34461. return true;
  34462. }
  34463. return this._scene.forcePointsCloud;
  34464. },
  34465. /**
  34466. * Sets the state of point cloud mode
  34467. */
  34468. set: function (value) {
  34469. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34470. },
  34471. enumerable: true,
  34472. configurable: true
  34473. });
  34474. Object.defineProperty(Material.prototype, "fillMode", {
  34475. /**
  34476. * Gets the material fill mode
  34477. */
  34478. get: function () {
  34479. return this._fillMode;
  34480. },
  34481. /**
  34482. * Sets the material fill mode
  34483. */
  34484. set: function (value) {
  34485. if (this._fillMode === value) {
  34486. return;
  34487. }
  34488. this._fillMode = value;
  34489. this.markAsDirty(Material.MiscDirtyFlag);
  34490. },
  34491. enumerable: true,
  34492. configurable: true
  34493. });
  34494. /**
  34495. * Returns a string representation of the current material
  34496. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34497. * @returns a string with material information
  34498. */
  34499. Material.prototype.toString = function (fullDetails) {
  34500. var ret = "Name: " + this.name;
  34501. if (fullDetails) {
  34502. }
  34503. return ret;
  34504. };
  34505. /**
  34506. * Gets the class name of the material
  34507. * @returns a string with the class name of the material
  34508. */
  34509. Material.prototype.getClassName = function () {
  34510. return "Material";
  34511. };
  34512. Object.defineProperty(Material.prototype, "isFrozen", {
  34513. /**
  34514. * Specifies if updates for the material been locked
  34515. */
  34516. get: function () {
  34517. return this.checkReadyOnlyOnce;
  34518. },
  34519. enumerable: true,
  34520. configurable: true
  34521. });
  34522. /**
  34523. * Locks updates for the material
  34524. */
  34525. Material.prototype.freeze = function () {
  34526. this.checkReadyOnlyOnce = true;
  34527. };
  34528. /**
  34529. * Unlocks updates for the material
  34530. */
  34531. Material.prototype.unfreeze = function () {
  34532. this.checkReadyOnlyOnce = false;
  34533. };
  34534. /**
  34535. * Specifies if the material is ready to be used
  34536. * @param mesh defines the mesh to check
  34537. * @param useInstances specifies if instances should be used
  34538. * @returns a boolean indicating if the material is ready to be used
  34539. */
  34540. Material.prototype.isReady = function (mesh, useInstances) {
  34541. return true;
  34542. };
  34543. /**
  34544. * Specifies that the submesh is ready to be used
  34545. * @param mesh defines the mesh to check
  34546. * @param subMesh defines which submesh to check
  34547. * @param useInstances specifies that instances should be used
  34548. * @returns a boolean indicating that the submesh is ready or not
  34549. */
  34550. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34551. return false;
  34552. };
  34553. /**
  34554. * Returns the material effect
  34555. * @returns the effect associated with the material
  34556. */
  34557. Material.prototype.getEffect = function () {
  34558. return this._effect;
  34559. };
  34560. /**
  34561. * Returns the current scene
  34562. * @returns a Scene
  34563. */
  34564. Material.prototype.getScene = function () {
  34565. return this._scene;
  34566. };
  34567. /**
  34568. * Specifies if the material will require alpha blending
  34569. * @returns a boolean specifying if alpha blending is needed
  34570. */
  34571. Material.prototype.needAlphaBlending = function () {
  34572. return (this.alpha < 1.0);
  34573. };
  34574. /**
  34575. * Specifies if the mesh will require alpha blending
  34576. * @param mesh defines the mesh to check
  34577. * @returns a boolean specifying if alpha blending is needed for the mesh
  34578. */
  34579. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34580. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34581. };
  34582. /**
  34583. * Specifies if this material should be rendered in alpha test mode
  34584. * @returns a boolean specifying if an alpha test is needed.
  34585. */
  34586. Material.prototype.needAlphaTesting = function () {
  34587. return false;
  34588. };
  34589. /**
  34590. * Gets the texture used for the alpha test
  34591. * @returns the texture to use for alpha testing
  34592. */
  34593. Material.prototype.getAlphaTestTexture = function () {
  34594. return null;
  34595. };
  34596. /**
  34597. * Marks the material to indicate that it needs to be re-calculated
  34598. */
  34599. Material.prototype.markDirty = function () {
  34600. this._wasPreviouslyReady = false;
  34601. };
  34602. /** @ignore */
  34603. Material.prototype._preBind = function (effect, overrideOrientation) {
  34604. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34605. var engine = this._scene.getEngine();
  34606. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34607. var reverse = orientation === Material.ClockWiseSideOrientation;
  34608. engine.enableEffect(effect ? effect : this._effect);
  34609. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34610. return reverse;
  34611. };
  34612. /**
  34613. * Binds the material to the mesh
  34614. * @param world defines the world transformation matrix
  34615. * @param mesh defines the mesh to bind the material to
  34616. */
  34617. Material.prototype.bind = function (world, mesh) {
  34618. };
  34619. /**
  34620. * Binds the submesh to the material
  34621. * @param world defines the world transformation matrix
  34622. * @param mesh defines the mesh containing the submesh
  34623. * @param subMesh defines the submesh to bind the material to
  34624. */
  34625. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34626. };
  34627. /**
  34628. * Binds the world matrix to the material
  34629. * @param world defines the world transformation matrix
  34630. */
  34631. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34632. };
  34633. /**
  34634. * Binds the scene's uniform buffer to the effect.
  34635. * @param effect defines the effect to bind to the scene uniform buffer
  34636. * @param sceneUbo defines the uniform buffer storing scene data
  34637. */
  34638. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34639. sceneUbo.bindToEffect(effect, "Scene");
  34640. };
  34641. /**
  34642. * Binds the view matrix to the effect
  34643. * @param effect defines the effect to bind the view matrix to
  34644. */
  34645. Material.prototype.bindView = function (effect) {
  34646. if (!this._useUBO) {
  34647. effect.setMatrix("view", this.getScene().getViewMatrix());
  34648. }
  34649. else {
  34650. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34651. }
  34652. };
  34653. /**
  34654. * Binds the view projection matrix to the effect
  34655. * @param effect defines the effect to bind the view projection matrix to
  34656. */
  34657. Material.prototype.bindViewProjection = function (effect) {
  34658. if (!this._useUBO) {
  34659. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34660. }
  34661. else {
  34662. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34663. }
  34664. };
  34665. /**
  34666. * Specifies if material alpha testing should be turned on for the mesh
  34667. * @param mesh defines the mesh to check
  34668. */
  34669. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34670. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34671. };
  34672. /**
  34673. * Processes to execute after binding the material to a mesh
  34674. * @param mesh defines the rendered mesh
  34675. */
  34676. Material.prototype._afterBind = function (mesh) {
  34677. this._scene._cachedMaterial = this;
  34678. if (mesh) {
  34679. this._scene._cachedVisibility = mesh.visibility;
  34680. }
  34681. else {
  34682. this._scene._cachedVisibility = 1;
  34683. }
  34684. if (mesh) {
  34685. this.onBindObservable.notifyObservers(mesh);
  34686. }
  34687. if (this.disableDepthWrite) {
  34688. var engine = this._scene.getEngine();
  34689. this._cachedDepthWriteState = engine.getDepthWrite();
  34690. engine.setDepthWrite(false);
  34691. }
  34692. };
  34693. /**
  34694. * Unbinds the material from the mesh
  34695. */
  34696. Material.prototype.unbind = function () {
  34697. this.onUnBindObservable.notifyObservers(this);
  34698. if (this.disableDepthWrite) {
  34699. var engine = this._scene.getEngine();
  34700. engine.setDepthWrite(this._cachedDepthWriteState);
  34701. }
  34702. };
  34703. /**
  34704. * Gets the active textures from the material
  34705. * @returns an array of textures
  34706. */
  34707. Material.prototype.getActiveTextures = function () {
  34708. return [];
  34709. };
  34710. /**
  34711. * Specifies if the material uses a texture
  34712. * @param texture defines the texture to check against the material
  34713. * @returns a boolean specifying if the material uses the texture
  34714. */
  34715. Material.prototype.hasTexture = function (texture) {
  34716. return false;
  34717. };
  34718. /**
  34719. * Makes a duplicate of the material, and gives it a new name
  34720. * @param name defines the new name for the duplicated material
  34721. * @returns the cloned material
  34722. */
  34723. Material.prototype.clone = function (name) {
  34724. return null;
  34725. };
  34726. /**
  34727. * Gets the meshes bound to the material
  34728. * @returns an array of meshes bound to the material
  34729. */
  34730. Material.prototype.getBindedMeshes = function () {
  34731. var result = new Array();
  34732. for (var index = 0; index < this._scene.meshes.length; index++) {
  34733. var mesh = this._scene.meshes[index];
  34734. if (mesh.material === this) {
  34735. result.push(mesh);
  34736. }
  34737. }
  34738. return result;
  34739. };
  34740. /**
  34741. * Force shader compilation
  34742. * @param mesh defines the mesh associated with this material
  34743. * @param onCompiled defines a function to execute once the material is compiled
  34744. * @param options defines the options to configure the compilation
  34745. */
  34746. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34747. var _this = this;
  34748. var localOptions = __assign({ clipPlane: false }, options);
  34749. var subMesh = new BABYLON.BaseSubMesh();
  34750. var scene = this.getScene();
  34751. var checkReady = function () {
  34752. if (!_this._scene || !_this._scene.getEngine()) {
  34753. return;
  34754. }
  34755. if (subMesh._materialDefines) {
  34756. subMesh._materialDefines._renderId = -1;
  34757. }
  34758. var clipPlaneState = scene.clipPlane;
  34759. if (localOptions.clipPlane) {
  34760. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34761. }
  34762. if (_this.storeEffectOnSubMeshes) {
  34763. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34764. if (onCompiled) {
  34765. onCompiled(_this);
  34766. }
  34767. }
  34768. else {
  34769. setTimeout(checkReady, 16);
  34770. }
  34771. }
  34772. else {
  34773. if (_this.isReady(mesh)) {
  34774. if (onCompiled) {
  34775. onCompiled(_this);
  34776. }
  34777. }
  34778. else {
  34779. setTimeout(checkReady, 16);
  34780. }
  34781. }
  34782. if (localOptions.clipPlane) {
  34783. scene.clipPlane = clipPlaneState;
  34784. }
  34785. };
  34786. checkReady();
  34787. };
  34788. /**
  34789. * Force shader compilation
  34790. * @param mesh defines the mesh that will use this material
  34791. * @param options defines additional options for compiling the shaders
  34792. * @returns a promise that resolves when the compilation completes
  34793. */
  34794. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34795. var _this = this;
  34796. return new Promise(function (resolve) {
  34797. _this.forceCompilation(mesh, function () {
  34798. resolve();
  34799. }, options);
  34800. });
  34801. };
  34802. /**
  34803. * Marks a define in the material to indicate that it needs to be re-computed
  34804. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34805. */
  34806. Material.prototype.markAsDirty = function (flag) {
  34807. if (flag & Material.TextureDirtyFlag) {
  34808. this._markAllSubMeshesAsTexturesDirty();
  34809. }
  34810. if (flag & Material.LightDirtyFlag) {
  34811. this._markAllSubMeshesAsLightsDirty();
  34812. }
  34813. if (flag & Material.FresnelDirtyFlag) {
  34814. this._markAllSubMeshesAsFresnelDirty();
  34815. }
  34816. if (flag & Material.AttributesDirtyFlag) {
  34817. this._markAllSubMeshesAsAttributesDirty();
  34818. }
  34819. if (flag & Material.MiscDirtyFlag) {
  34820. this._markAllSubMeshesAsMiscDirty();
  34821. }
  34822. this.getScene().resetCachedMaterial();
  34823. };
  34824. /**
  34825. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34826. * @param func defines a function which checks material defines against the submeshes
  34827. */
  34828. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34829. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34830. var mesh = _a[_i];
  34831. if (!mesh.subMeshes) {
  34832. continue;
  34833. }
  34834. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34835. var subMesh = _c[_b];
  34836. if (subMesh.getMaterial() !== this) {
  34837. continue;
  34838. }
  34839. if (!subMesh._materialDefines) {
  34840. continue;
  34841. }
  34842. func(subMesh._materialDefines);
  34843. }
  34844. }
  34845. };
  34846. /**
  34847. * Indicates that image processing needs to be re-calculated for all submeshes
  34848. */
  34849. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34850. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34851. };
  34852. /**
  34853. * Indicates that textures need to be re-calculated for all submeshes
  34854. */
  34855. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34856. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34857. };
  34858. /**
  34859. * Indicates that fresnel needs to be re-calculated for all submeshes
  34860. */
  34861. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34862. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34863. };
  34864. /**
  34865. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34866. */
  34867. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34868. this._markAllSubMeshesAsDirty(function (defines) {
  34869. defines.markAsFresnelDirty();
  34870. defines.markAsMiscDirty();
  34871. });
  34872. };
  34873. /**
  34874. * Indicates that lights need to be re-calculated for all submeshes
  34875. */
  34876. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34877. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34878. };
  34879. /**
  34880. * Indicates that attributes need to be re-calculated for all submeshes
  34881. */
  34882. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34883. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34884. };
  34885. /**
  34886. * Indicates that misc needs to be re-calculated for all submeshes
  34887. */
  34888. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34889. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34890. };
  34891. /**
  34892. * Indicates that textures and misc need to be re-calculated for all submeshes
  34893. */
  34894. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34895. this._markAllSubMeshesAsDirty(function (defines) {
  34896. defines.markAsTexturesDirty();
  34897. defines.markAsMiscDirty();
  34898. });
  34899. };
  34900. /**
  34901. * Disposes the material
  34902. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34903. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34904. */
  34905. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34906. // Animations
  34907. this.getScene().stopAnimation(this);
  34908. this.getScene().freeProcessedMaterials();
  34909. // Remove from scene
  34910. var index = this._scene.materials.indexOf(this);
  34911. if (index >= 0) {
  34912. this._scene.materials.splice(index, 1);
  34913. }
  34914. // Remove from meshes
  34915. for (index = 0; index < this._scene.meshes.length; index++) {
  34916. var mesh = this._scene.meshes[index];
  34917. if (mesh.material === this) {
  34918. mesh.material = null;
  34919. if (mesh.geometry) {
  34920. var geometry = (mesh.geometry);
  34921. if (this.storeEffectOnSubMeshes) {
  34922. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34923. var subMesh = _a[_i];
  34924. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34925. if (forceDisposeEffect && subMesh._materialEffect) {
  34926. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34927. }
  34928. }
  34929. }
  34930. else {
  34931. geometry._releaseVertexArrayObject(this._effect);
  34932. }
  34933. }
  34934. }
  34935. }
  34936. this._uniformBuffer.dispose();
  34937. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34938. if (forceDisposeEffect && this._effect) {
  34939. if (!this.storeEffectOnSubMeshes) {
  34940. this._scene.getEngine()._releaseEffect(this._effect);
  34941. }
  34942. this._effect = null;
  34943. }
  34944. // Callback
  34945. this.onDisposeObservable.notifyObservers(this);
  34946. this.onDisposeObservable.clear();
  34947. this.onBindObservable.clear();
  34948. this.onUnBindObservable.clear();
  34949. };
  34950. /**
  34951. * Serializes this material
  34952. * @returns the serialized material object
  34953. */
  34954. Material.prototype.serialize = function () {
  34955. return BABYLON.SerializationHelper.Serialize(this);
  34956. };
  34957. /**
  34958. * Creates a MultiMaterial from parsed MultiMaterial data.
  34959. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34960. * @param scene defines the hosting scene
  34961. * @returns a new MultiMaterial
  34962. */
  34963. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34964. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34965. multiMaterial.id = parsedMultiMaterial.id;
  34966. if (BABYLON.Tags) {
  34967. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34968. }
  34969. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34970. var subMatId = parsedMultiMaterial.materials[matIndex];
  34971. if (subMatId) {
  34972. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34973. }
  34974. else {
  34975. multiMaterial.subMaterials.push(null);
  34976. }
  34977. }
  34978. return multiMaterial;
  34979. };
  34980. /**
  34981. * Creates a material from parsed material data
  34982. * @param parsedMaterial defines parsed material data
  34983. * @param scene defines the hosting scene
  34984. * @param rootUrl defines the root URL to use to load textures
  34985. * @returns a new material
  34986. */
  34987. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34988. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34989. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34990. }
  34991. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34992. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34993. if (!BABYLON.LegacyPBRMaterial) {
  34994. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34995. return;
  34996. }
  34997. }
  34998. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34999. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35000. ;
  35001. };
  35002. // Triangle views
  35003. Material._TriangleFillMode = 0;
  35004. Material._WireFrameFillMode = 1;
  35005. Material._PointFillMode = 2;
  35006. // Draw modes
  35007. Material._PointListDrawMode = 3;
  35008. Material._LineListDrawMode = 4;
  35009. Material._LineLoopDrawMode = 5;
  35010. Material._LineStripDrawMode = 6;
  35011. Material._TriangleStripDrawMode = 7;
  35012. Material._TriangleFanDrawMode = 8;
  35013. /**
  35014. * Stores the clock-wise side orientation
  35015. */
  35016. Material._ClockWiseSideOrientation = 0;
  35017. /**
  35018. * Stores the counter clock-wise side orientation
  35019. */
  35020. Material._CounterClockWiseSideOrientation = 1;
  35021. /**
  35022. * The dirty texture flag value
  35023. */
  35024. Material._TextureDirtyFlag = 1;
  35025. /**
  35026. * The dirty light flag value
  35027. */
  35028. Material._LightDirtyFlag = 2;
  35029. /**
  35030. * The dirty fresnel flag value
  35031. */
  35032. Material._FresnelDirtyFlag = 4;
  35033. /**
  35034. * The dirty attribute flag value
  35035. */
  35036. Material._AttributesDirtyFlag = 8;
  35037. /**
  35038. * The dirty misc flag value
  35039. */
  35040. Material._MiscDirtyFlag = 16;
  35041. __decorate([
  35042. BABYLON.serialize()
  35043. ], Material.prototype, "id", void 0);
  35044. __decorate([
  35045. BABYLON.serialize()
  35046. ], Material.prototype, "name", void 0);
  35047. __decorate([
  35048. BABYLON.serialize()
  35049. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35050. __decorate([
  35051. BABYLON.serialize()
  35052. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35053. __decorate([
  35054. BABYLON.serialize()
  35055. ], Material.prototype, "state", void 0);
  35056. __decorate([
  35057. BABYLON.serialize("alpha")
  35058. ], Material.prototype, "_alpha", void 0);
  35059. __decorate([
  35060. BABYLON.serialize("backFaceCulling")
  35061. ], Material.prototype, "_backFaceCulling", void 0);
  35062. __decorate([
  35063. BABYLON.serialize()
  35064. ], Material.prototype, "sideOrientation", void 0);
  35065. __decorate([
  35066. BABYLON.serialize("alphaMode")
  35067. ], Material.prototype, "_alphaMode", void 0);
  35068. __decorate([
  35069. BABYLON.serialize()
  35070. ], Material.prototype, "_needDepthPrePass", void 0);
  35071. __decorate([
  35072. BABYLON.serialize()
  35073. ], Material.prototype, "disableDepthWrite", void 0);
  35074. __decorate([
  35075. BABYLON.serialize()
  35076. ], Material.prototype, "forceDepthWrite", void 0);
  35077. __decorate([
  35078. BABYLON.serialize()
  35079. ], Material.prototype, "separateCullingPass", void 0);
  35080. __decorate([
  35081. BABYLON.serialize("fogEnabled")
  35082. ], Material.prototype, "_fogEnabled", void 0);
  35083. __decorate([
  35084. BABYLON.serialize()
  35085. ], Material.prototype, "pointSize", void 0);
  35086. __decorate([
  35087. BABYLON.serialize()
  35088. ], Material.prototype, "zOffset", void 0);
  35089. __decorate([
  35090. BABYLON.serialize()
  35091. ], Material.prototype, "wireframe", null);
  35092. __decorate([
  35093. BABYLON.serialize()
  35094. ], Material.prototype, "pointsCloud", null);
  35095. __decorate([
  35096. BABYLON.serialize()
  35097. ], Material.prototype, "fillMode", null);
  35098. return Material;
  35099. }());
  35100. BABYLON.Material = Material;
  35101. })(BABYLON || (BABYLON = {}));
  35102. //# sourceMappingURL=babylon.material.js.map
  35103. var BABYLON;
  35104. (function (BABYLON) {
  35105. var UniformBuffer = /** @class */ (function () {
  35106. /**
  35107. * Uniform buffer objects.
  35108. *
  35109. * Handles blocks of uniform on the GPU.
  35110. *
  35111. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35112. *
  35113. * For more information, please refer to :
  35114. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35115. */
  35116. function UniformBuffer(engine, data, dynamic) {
  35117. this._engine = engine;
  35118. this._noUBO = !engine.supportsUniformBuffers;
  35119. this._dynamic = dynamic;
  35120. this._data = data || [];
  35121. this._uniformLocations = {};
  35122. this._uniformSizes = {};
  35123. this._uniformLocationPointer = 0;
  35124. this._needSync = false;
  35125. if (this._noUBO) {
  35126. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35127. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35128. this.updateFloat = this._updateFloatForEffect;
  35129. this.updateFloat2 = this._updateFloat2ForEffect;
  35130. this.updateFloat3 = this._updateFloat3ForEffect;
  35131. this.updateFloat4 = this._updateFloat4ForEffect;
  35132. this.updateMatrix = this._updateMatrixForEffect;
  35133. this.updateVector3 = this._updateVector3ForEffect;
  35134. this.updateVector4 = this._updateVector4ForEffect;
  35135. this.updateColor3 = this._updateColor3ForEffect;
  35136. this.updateColor4 = this._updateColor4ForEffect;
  35137. }
  35138. else {
  35139. this._engine._uniformBuffers.push(this);
  35140. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35141. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35142. this.updateFloat = this._updateFloatForUniform;
  35143. this.updateFloat2 = this._updateFloat2ForUniform;
  35144. this.updateFloat3 = this._updateFloat3ForUniform;
  35145. this.updateFloat4 = this._updateFloat4ForUniform;
  35146. this.updateMatrix = this._updateMatrixForUniform;
  35147. this.updateVector3 = this._updateVector3ForUniform;
  35148. this.updateVector4 = this._updateVector4ForUniform;
  35149. this.updateColor3 = this._updateColor3ForUniform;
  35150. this.updateColor4 = this._updateColor4ForUniform;
  35151. }
  35152. }
  35153. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35154. // Properties
  35155. /**
  35156. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35157. * or just falling back on setUniformXXX calls.
  35158. */
  35159. get: function () {
  35160. return !this._noUBO;
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35166. /**
  35167. * Indicates if the WebGL underlying uniform buffer is in sync
  35168. * with the javascript cache data.
  35169. */
  35170. get: function () {
  35171. return !this._needSync;
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. /**
  35177. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35178. * Also, a dynamic UniformBuffer will disable cache verification and always
  35179. * update the underlying WebGL uniform buffer to the GPU.
  35180. */
  35181. UniformBuffer.prototype.isDynamic = function () {
  35182. return this._dynamic !== undefined;
  35183. };
  35184. /**
  35185. * The data cache on JS side.
  35186. */
  35187. UniformBuffer.prototype.getData = function () {
  35188. return this._bufferData;
  35189. };
  35190. /**
  35191. * The underlying WebGL Uniform buffer.
  35192. */
  35193. UniformBuffer.prototype.getBuffer = function () {
  35194. return this._buffer;
  35195. };
  35196. /**
  35197. * std140 layout specifies how to align data within an UBO structure.
  35198. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35199. * for specs.
  35200. */
  35201. UniformBuffer.prototype._fillAlignment = function (size) {
  35202. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35203. // and 4x4 matrices
  35204. // TODO : change if other types are used
  35205. var alignment;
  35206. if (size <= 2) {
  35207. alignment = size;
  35208. }
  35209. else {
  35210. alignment = 4;
  35211. }
  35212. if ((this._uniformLocationPointer % alignment) !== 0) {
  35213. var oldPointer = this._uniformLocationPointer;
  35214. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35215. var diff = this._uniformLocationPointer - oldPointer;
  35216. for (var i = 0; i < diff; i++) {
  35217. this._data.push(0);
  35218. }
  35219. }
  35220. };
  35221. /**
  35222. * Adds an uniform in the buffer.
  35223. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35224. * for the layout to be correct !
  35225. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35226. * @param {number|number[]} size Data size, or data directly.
  35227. */
  35228. UniformBuffer.prototype.addUniform = function (name, size) {
  35229. if (this._noUBO) {
  35230. return;
  35231. }
  35232. if (this._uniformLocations[name] !== undefined) {
  35233. // Already existing uniform
  35234. return;
  35235. }
  35236. // This function must be called in the order of the shader layout !
  35237. // size can be the size of the uniform, or data directly
  35238. var data;
  35239. if (size instanceof Array) {
  35240. data = size;
  35241. size = data.length;
  35242. }
  35243. else {
  35244. size = size;
  35245. data = [];
  35246. // Fill with zeros
  35247. for (var i = 0; i < size; i++) {
  35248. data.push(0);
  35249. }
  35250. }
  35251. this._fillAlignment(size);
  35252. this._uniformSizes[name] = size;
  35253. this._uniformLocations[name] = this._uniformLocationPointer;
  35254. this._uniformLocationPointer += size;
  35255. for (var i = 0; i < size; i++) {
  35256. this._data.push(data[i]);
  35257. }
  35258. this._needSync = true;
  35259. };
  35260. /**
  35261. * Wrapper for addUniform.
  35262. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35263. * @param {Matrix} mat A 4x4 matrix.
  35264. */
  35265. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35266. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35267. };
  35268. /**
  35269. * Wrapper for addUniform.
  35270. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35271. * @param {number} x
  35272. * @param {number} y
  35273. */
  35274. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35275. var temp = [x, y];
  35276. this.addUniform(name, temp);
  35277. };
  35278. /**
  35279. * Wrapper for addUniform.
  35280. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35281. * @param {number} x
  35282. * @param {number} y
  35283. * @param {number} z
  35284. */
  35285. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35286. var temp = [x, y, z];
  35287. this.addUniform(name, temp);
  35288. };
  35289. /**
  35290. * Wrapper for addUniform.
  35291. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35292. * @param {Color3} color
  35293. */
  35294. UniformBuffer.prototype.addColor3 = function (name, color) {
  35295. var temp = new Array();
  35296. color.toArray(temp);
  35297. this.addUniform(name, temp);
  35298. };
  35299. /**
  35300. * Wrapper for addUniform.
  35301. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35302. * @param {Color3} color
  35303. * @param {number} alpha
  35304. */
  35305. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35306. var temp = new Array();
  35307. color.toArray(temp);
  35308. temp.push(alpha);
  35309. this.addUniform(name, temp);
  35310. };
  35311. /**
  35312. * Wrapper for addUniform.
  35313. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35314. * @param {Vector3} vector
  35315. */
  35316. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35317. var temp = new Array();
  35318. vector.toArray(temp);
  35319. this.addUniform(name, temp);
  35320. };
  35321. /**
  35322. * Wrapper for addUniform.
  35323. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35324. */
  35325. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35326. this.addUniform(name, 12);
  35327. };
  35328. /**
  35329. * Wrapper for addUniform.
  35330. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35331. */
  35332. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35333. this.addUniform(name, 8);
  35334. };
  35335. /**
  35336. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35337. */
  35338. UniformBuffer.prototype.create = function () {
  35339. if (this._noUBO) {
  35340. return;
  35341. }
  35342. if (this._buffer) {
  35343. return; // nothing to do
  35344. }
  35345. // See spec, alignment must be filled as a vec4
  35346. this._fillAlignment(4);
  35347. this._bufferData = new Float32Array(this._data);
  35348. this._rebuild();
  35349. this._needSync = true;
  35350. };
  35351. UniformBuffer.prototype._rebuild = function () {
  35352. if (this._noUBO) {
  35353. return;
  35354. }
  35355. if (this._dynamic) {
  35356. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35357. }
  35358. else {
  35359. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35360. }
  35361. };
  35362. /**
  35363. * Updates the WebGL Uniform Buffer on the GPU.
  35364. * If the `dynamic` flag is set to true, no cache comparison is done.
  35365. * Otherwise, the buffer will be updated only if the cache differs.
  35366. */
  35367. UniformBuffer.prototype.update = function () {
  35368. if (!this._buffer) {
  35369. this.create();
  35370. return;
  35371. }
  35372. if (!this._dynamic && !this._needSync) {
  35373. return;
  35374. }
  35375. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35376. this._needSync = false;
  35377. };
  35378. /**
  35379. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35380. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35381. * @param {number[]|Float32Array} data Flattened data
  35382. * @param {number} size Size of the data.
  35383. */
  35384. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35385. var location = this._uniformLocations[uniformName];
  35386. if (location === undefined) {
  35387. if (this._buffer) {
  35388. // Cannot add an uniform if the buffer is already created
  35389. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35390. return;
  35391. }
  35392. this.addUniform(uniformName, size);
  35393. location = this._uniformLocations[uniformName];
  35394. }
  35395. if (!this._buffer) {
  35396. this.create();
  35397. }
  35398. if (!this._dynamic) {
  35399. // Cache for static uniform buffers
  35400. var changed = false;
  35401. for (var i = 0; i < size; i++) {
  35402. if (this._bufferData[location + i] !== data[i]) {
  35403. changed = true;
  35404. this._bufferData[location + i] = data[i];
  35405. }
  35406. }
  35407. this._needSync = this._needSync || changed;
  35408. }
  35409. else {
  35410. // No cache for dynamic
  35411. for (var i = 0; i < size; i++) {
  35412. this._bufferData[location + i] = data[i];
  35413. }
  35414. }
  35415. };
  35416. // Update methods
  35417. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35418. // To match std140, matrix must be realigned
  35419. for (var i = 0; i < 3; i++) {
  35420. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35421. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35422. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35423. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35424. }
  35425. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35426. };
  35427. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35428. this._currentEffect.setMatrix3x3(name, matrix);
  35429. };
  35430. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35431. this._currentEffect.setMatrix2x2(name, matrix);
  35432. };
  35433. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35434. // To match std140, matrix must be realigned
  35435. for (var i = 0; i < 2; i++) {
  35436. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35437. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35438. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35439. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35440. }
  35441. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35442. };
  35443. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35444. this._currentEffect.setFloat(name, x);
  35445. };
  35446. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35447. UniformBuffer._tempBuffer[0] = x;
  35448. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35449. };
  35450. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35451. if (suffix === void 0) { suffix = ""; }
  35452. this._currentEffect.setFloat2(name + suffix, x, y);
  35453. };
  35454. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35455. if (suffix === void 0) { suffix = ""; }
  35456. UniformBuffer._tempBuffer[0] = x;
  35457. UniformBuffer._tempBuffer[1] = y;
  35458. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35459. };
  35460. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35461. if (suffix === void 0) { suffix = ""; }
  35462. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35463. };
  35464. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35465. if (suffix === void 0) { suffix = ""; }
  35466. UniformBuffer._tempBuffer[0] = x;
  35467. UniformBuffer._tempBuffer[1] = y;
  35468. UniformBuffer._tempBuffer[2] = z;
  35469. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35470. };
  35471. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35472. if (suffix === void 0) { suffix = ""; }
  35473. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35474. };
  35475. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35476. if (suffix === void 0) { suffix = ""; }
  35477. UniformBuffer._tempBuffer[0] = x;
  35478. UniformBuffer._tempBuffer[1] = y;
  35479. UniformBuffer._tempBuffer[2] = z;
  35480. UniformBuffer._tempBuffer[3] = w;
  35481. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35482. };
  35483. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35484. this._currentEffect.setMatrix(name, mat);
  35485. };
  35486. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35487. this.updateUniform(name, mat.toArray(), 16);
  35488. };
  35489. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35490. this._currentEffect.setVector3(name, vector);
  35491. };
  35492. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35493. vector.toArray(UniformBuffer._tempBuffer);
  35494. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35495. };
  35496. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35497. this._currentEffect.setVector4(name, vector);
  35498. };
  35499. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35500. vector.toArray(UniformBuffer._tempBuffer);
  35501. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35502. };
  35503. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35504. if (suffix === void 0) { suffix = ""; }
  35505. this._currentEffect.setColor3(name + suffix, color);
  35506. };
  35507. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35508. if (suffix === void 0) { suffix = ""; }
  35509. color.toArray(UniformBuffer._tempBuffer);
  35510. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35511. };
  35512. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35513. if (suffix === void 0) { suffix = ""; }
  35514. this._currentEffect.setColor4(name + suffix, color, alpha);
  35515. };
  35516. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35517. if (suffix === void 0) { suffix = ""; }
  35518. color.toArray(UniformBuffer._tempBuffer);
  35519. UniformBuffer._tempBuffer[3] = alpha;
  35520. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35521. };
  35522. /**
  35523. * Sets a sampler uniform on the effect.
  35524. * @param {string} name Name of the sampler.
  35525. * @param {Texture} texture
  35526. */
  35527. UniformBuffer.prototype.setTexture = function (name, texture) {
  35528. this._currentEffect.setTexture(name, texture);
  35529. };
  35530. /**
  35531. * Directly updates the value of the uniform in the cache AND on the GPU.
  35532. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35533. * @param {number[]|Float32Array} data Flattened data
  35534. */
  35535. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35536. this.updateUniform(uniformName, data, data.length);
  35537. this.update();
  35538. };
  35539. /**
  35540. * Binds this uniform buffer to an effect.
  35541. * @param {Effect} effect
  35542. * @param {string} name Name of the uniform block in the shader.
  35543. */
  35544. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35545. this._currentEffect = effect;
  35546. if (this._noUBO || !this._buffer) {
  35547. return;
  35548. }
  35549. effect.bindUniformBuffer(this._buffer, name);
  35550. };
  35551. /**
  35552. * Disposes the uniform buffer.
  35553. */
  35554. UniformBuffer.prototype.dispose = function () {
  35555. if (this._noUBO) {
  35556. return;
  35557. }
  35558. var index = this._engine._uniformBuffers.indexOf(this);
  35559. if (index !== -1) {
  35560. this._engine._uniformBuffers.splice(index, 1);
  35561. }
  35562. if (!this._buffer) {
  35563. return;
  35564. }
  35565. if (this._engine._releaseBuffer(this._buffer)) {
  35566. this._buffer = null;
  35567. }
  35568. };
  35569. // Pool for avoiding memory leaks
  35570. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35571. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35572. return UniformBuffer;
  35573. }());
  35574. BABYLON.UniformBuffer = UniformBuffer;
  35575. })(BABYLON || (BABYLON = {}));
  35576. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35577. var BABYLON;
  35578. (function (BABYLON) {
  35579. /**
  35580. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35581. */
  35582. var VertexData = /** @class */ (function () {
  35583. function VertexData() {
  35584. }
  35585. /**
  35586. * Uses the passed data array to set the set the values for the specified kind of data
  35587. * @param data a linear array of floating numbers
  35588. * @param kind the type of data that is being set, eg positions, colors etc
  35589. */
  35590. VertexData.prototype.set = function (data, kind) {
  35591. switch (kind) {
  35592. case BABYLON.VertexBuffer.PositionKind:
  35593. this.positions = data;
  35594. break;
  35595. case BABYLON.VertexBuffer.NormalKind:
  35596. this.normals = data;
  35597. break;
  35598. case BABYLON.VertexBuffer.TangentKind:
  35599. this.tangents = data;
  35600. break;
  35601. case BABYLON.VertexBuffer.UVKind:
  35602. this.uvs = data;
  35603. break;
  35604. case BABYLON.VertexBuffer.UV2Kind:
  35605. this.uvs2 = data;
  35606. break;
  35607. case BABYLON.VertexBuffer.UV3Kind:
  35608. this.uvs3 = data;
  35609. break;
  35610. case BABYLON.VertexBuffer.UV4Kind:
  35611. this.uvs4 = data;
  35612. break;
  35613. case BABYLON.VertexBuffer.UV5Kind:
  35614. this.uvs5 = data;
  35615. break;
  35616. case BABYLON.VertexBuffer.UV6Kind:
  35617. this.uvs6 = data;
  35618. break;
  35619. case BABYLON.VertexBuffer.ColorKind:
  35620. this.colors = data;
  35621. break;
  35622. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35623. this.matricesIndices = data;
  35624. break;
  35625. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35626. this.matricesWeights = data;
  35627. break;
  35628. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35629. this.matricesIndicesExtra = data;
  35630. break;
  35631. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35632. this.matricesWeightsExtra = data;
  35633. break;
  35634. }
  35635. };
  35636. /**
  35637. * Associates the vertexData to the passed Mesh.
  35638. * Sets it as updatable or not (default `false`)
  35639. * @param mesh the mesh the vertexData is applied to
  35640. * @param updatable when used and having the value true allows new data to update the vertexData
  35641. * @returns the VertexData
  35642. */
  35643. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35644. this._applyTo(mesh, updatable);
  35645. return this;
  35646. };
  35647. /**
  35648. * Associates the vertexData to the passed Geometry.
  35649. * Sets it as updatable or not (default `false`)
  35650. * @param geometry the geometry the vertexData is applied to
  35651. * @param updatable when used and having the value true allows new data to update the vertexData
  35652. * @returns VertexData
  35653. */
  35654. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35655. this._applyTo(geometry, updatable);
  35656. return this;
  35657. };
  35658. /**
  35659. * Updates the associated mesh
  35660. * @param mesh the mesh to be updated
  35661. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35662. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35663. * @returns VertexData
  35664. */
  35665. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35666. this._update(mesh);
  35667. return this;
  35668. };
  35669. /**
  35670. * Updates the associated geometry
  35671. * @param geometry the geometry to be updated
  35672. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35673. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  35674. * @returns VertexData.
  35675. */
  35676. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35677. this._update(geometry);
  35678. return this;
  35679. };
  35680. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35681. if (updatable === void 0) { updatable = false; }
  35682. if (this.positions) {
  35683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35684. }
  35685. if (this.normals) {
  35686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35687. }
  35688. if (this.tangents) {
  35689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35690. }
  35691. if (this.uvs) {
  35692. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35693. }
  35694. if (this.uvs2) {
  35695. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35696. }
  35697. if (this.uvs3) {
  35698. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35699. }
  35700. if (this.uvs4) {
  35701. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35702. }
  35703. if (this.uvs5) {
  35704. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35705. }
  35706. if (this.uvs6) {
  35707. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35708. }
  35709. if (this.colors) {
  35710. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35711. }
  35712. if (this.matricesIndices) {
  35713. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35714. }
  35715. if (this.matricesWeights) {
  35716. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35717. }
  35718. if (this.matricesIndicesExtra) {
  35719. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35720. }
  35721. if (this.matricesWeightsExtra) {
  35722. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35723. }
  35724. if (this.indices) {
  35725. meshOrGeometry.setIndices(this.indices, null, updatable);
  35726. }
  35727. return this;
  35728. };
  35729. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35730. if (this.positions) {
  35731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35732. }
  35733. if (this.normals) {
  35734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35735. }
  35736. if (this.tangents) {
  35737. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35738. }
  35739. if (this.uvs) {
  35740. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35741. }
  35742. if (this.uvs2) {
  35743. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35744. }
  35745. if (this.uvs3) {
  35746. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35747. }
  35748. if (this.uvs4) {
  35749. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35750. }
  35751. if (this.uvs5) {
  35752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35753. }
  35754. if (this.uvs6) {
  35755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35756. }
  35757. if (this.colors) {
  35758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35759. }
  35760. if (this.matricesIndices) {
  35761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35762. }
  35763. if (this.matricesWeights) {
  35764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35765. }
  35766. if (this.matricesIndicesExtra) {
  35767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35768. }
  35769. if (this.matricesWeightsExtra) {
  35770. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35771. }
  35772. if (this.indices) {
  35773. meshOrGeometry.setIndices(this.indices, null);
  35774. }
  35775. return this;
  35776. };
  35777. /**
  35778. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35779. * @param matrix the transforming matrix
  35780. * @returns the VertexData
  35781. */
  35782. VertexData.prototype.transform = function (matrix) {
  35783. var transformed = BABYLON.Vector3.Zero();
  35784. var index;
  35785. if (this.positions) {
  35786. var position = BABYLON.Vector3.Zero();
  35787. for (index = 0; index < this.positions.length; index += 3) {
  35788. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35789. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35790. this.positions[index] = transformed.x;
  35791. this.positions[index + 1] = transformed.y;
  35792. this.positions[index + 2] = transformed.z;
  35793. }
  35794. }
  35795. if (this.normals) {
  35796. var normal = BABYLON.Vector3.Zero();
  35797. for (index = 0; index < this.normals.length; index += 3) {
  35798. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35799. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35800. this.normals[index] = transformed.x;
  35801. this.normals[index + 1] = transformed.y;
  35802. this.normals[index + 2] = transformed.z;
  35803. }
  35804. }
  35805. if (this.tangents) {
  35806. var tangent = BABYLON.Vector4.Zero();
  35807. var tangentTransformed = BABYLON.Vector4.Zero();
  35808. for (index = 0; index < this.tangents.length; index += 4) {
  35809. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35810. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35811. this.tangents[index] = tangentTransformed.x;
  35812. this.tangents[index + 1] = tangentTransformed.y;
  35813. this.tangents[index + 2] = tangentTransformed.z;
  35814. this.tangents[index + 3] = tangentTransformed.w;
  35815. }
  35816. }
  35817. return this;
  35818. };
  35819. /**
  35820. * Merges the passed VertexData into the current one
  35821. * @param other the VertexData to be merged into the current one
  35822. * @returns the modified VertexData
  35823. */
  35824. VertexData.prototype.merge = function (other) {
  35825. this._validate();
  35826. other._validate();
  35827. if (!this.normals !== !other.normals ||
  35828. !this.tangents !== !other.tangents ||
  35829. !this.uvs !== !other.uvs ||
  35830. !this.uvs2 !== !other.uvs2 ||
  35831. !this.uvs3 !== !other.uvs3 ||
  35832. !this.uvs4 !== !other.uvs4 ||
  35833. !this.uvs5 !== !other.uvs5 ||
  35834. !this.uvs6 !== !other.uvs6 ||
  35835. !this.colors !== !other.colors ||
  35836. !this.matricesIndices !== !other.matricesIndices ||
  35837. !this.matricesWeights !== !other.matricesWeights ||
  35838. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35839. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35840. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35841. }
  35842. if (other.indices) {
  35843. if (!this.indices) {
  35844. this.indices = [];
  35845. }
  35846. var offset = this.positions ? this.positions.length / 3 : 0;
  35847. for (var index = 0; index < other.indices.length; index++) {
  35848. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35849. this.indices.push(other.indices[index] + offset);
  35850. }
  35851. }
  35852. this.positions = this._mergeElement(this.positions, other.positions);
  35853. this.normals = this._mergeElement(this.normals, other.normals);
  35854. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35855. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35856. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35857. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35858. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35859. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35860. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35861. this.colors = this._mergeElement(this.colors, other.colors);
  35862. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35863. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35864. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35865. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35866. return this;
  35867. };
  35868. VertexData.prototype._mergeElement = function (source, other) {
  35869. if (!source) {
  35870. return other;
  35871. }
  35872. if (!other) {
  35873. return source;
  35874. }
  35875. var len = other.length + source.length;
  35876. var isSrcTypedArray = source instanceof Float32Array;
  35877. var isOthTypedArray = other instanceof Float32Array;
  35878. // use non-loop method when the source is Float32Array
  35879. if (isSrcTypedArray) {
  35880. var ret32 = new Float32Array(len);
  35881. ret32.set(source);
  35882. ret32.set(other, source.length);
  35883. return ret32;
  35884. // source is number[], when other is also use concat
  35885. }
  35886. else if (!isOthTypedArray) {
  35887. return source.concat(other);
  35888. // source is a number[], but other is a Float32Array, loop required
  35889. }
  35890. else {
  35891. var ret = source.slice(0); // copy source to a separate array
  35892. for (var i = 0, len = other.length; i < len; i++) {
  35893. ret.push(other[i]);
  35894. }
  35895. return ret;
  35896. }
  35897. };
  35898. VertexData.prototype._validate = function () {
  35899. if (!this.positions) {
  35900. throw new Error("Positions are required");
  35901. }
  35902. var getElementCount = function (kind, values) {
  35903. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35904. if ((values.length % stride) !== 0) {
  35905. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35906. }
  35907. return values.length / stride;
  35908. };
  35909. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35910. var validateElementCount = function (kind, values) {
  35911. var elementCount = getElementCount(kind, values);
  35912. if (elementCount !== positionsElementCount) {
  35913. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35914. }
  35915. };
  35916. if (this.normals)
  35917. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35918. if (this.tangents)
  35919. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35920. if (this.uvs)
  35921. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35922. if (this.uvs2)
  35923. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35924. if (this.uvs3)
  35925. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35926. if (this.uvs4)
  35927. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35928. if (this.uvs5)
  35929. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35930. if (this.uvs6)
  35931. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35932. if (this.colors)
  35933. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35934. if (this.matricesIndices)
  35935. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35936. if (this.matricesWeights)
  35937. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35938. if (this.matricesIndicesExtra)
  35939. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35940. if (this.matricesWeightsExtra)
  35941. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35942. };
  35943. /**
  35944. * Serializes the VertexData
  35945. * @returns a serialized object
  35946. */
  35947. VertexData.prototype.serialize = function () {
  35948. var serializationObject = this.serialize();
  35949. if (this.positions) {
  35950. serializationObject.positions = this.positions;
  35951. }
  35952. if (this.normals) {
  35953. serializationObject.normals = this.normals;
  35954. }
  35955. if (this.tangents) {
  35956. serializationObject.tangents = this.tangents;
  35957. }
  35958. if (this.uvs) {
  35959. serializationObject.uvs = this.uvs;
  35960. }
  35961. if (this.uvs2) {
  35962. serializationObject.uvs2 = this.uvs2;
  35963. }
  35964. if (this.uvs3) {
  35965. serializationObject.uvs3 = this.uvs3;
  35966. }
  35967. if (this.uvs4) {
  35968. serializationObject.uvs4 = this.uvs4;
  35969. }
  35970. if (this.uvs5) {
  35971. serializationObject.uvs5 = this.uvs5;
  35972. }
  35973. if (this.uvs6) {
  35974. serializationObject.uvs6 = this.uvs6;
  35975. }
  35976. if (this.colors) {
  35977. serializationObject.colors = this.colors;
  35978. }
  35979. if (this.matricesIndices) {
  35980. serializationObject.matricesIndices = this.matricesIndices;
  35981. serializationObject.matricesIndices._isExpanded = true;
  35982. }
  35983. if (this.matricesWeights) {
  35984. serializationObject.matricesWeights = this.matricesWeights;
  35985. }
  35986. if (this.matricesIndicesExtra) {
  35987. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35988. serializationObject.matricesIndicesExtra._isExpanded = true;
  35989. }
  35990. if (this.matricesWeightsExtra) {
  35991. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35992. }
  35993. serializationObject.indices = this.indices;
  35994. return serializationObject;
  35995. };
  35996. // Statics
  35997. /**
  35998. * Extracts the vertexData from a mesh
  35999. * @param mesh the mesh from which to extract the VertexData
  36000. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36001. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36002. * @returns the object VertexData associated to the passed mesh
  36003. */
  36004. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36005. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36006. };
  36007. /**
  36008. * Extracts the vertexData from the geometry
  36009. * @param geometry the geometry from which to extract the VertexData
  36010. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36011. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36012. * @returns the object VertexData associated to the passed mesh
  36013. */
  36014. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36015. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36016. };
  36017. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36018. var result = new VertexData();
  36019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36020. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36021. }
  36022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36023. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36024. }
  36025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36026. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36027. }
  36028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36029. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36030. }
  36031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36032. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36033. }
  36034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36035. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36036. }
  36037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36038. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36039. }
  36040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36041. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36042. }
  36043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36044. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36045. }
  36046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36047. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36048. }
  36049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36050. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36051. }
  36052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36053. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36054. }
  36055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36056. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36057. }
  36058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36059. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36060. }
  36061. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36062. return result;
  36063. };
  36064. /**
  36065. * Creates the VertexData for a Ribbon
  36066. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36067. * * pathArray array of paths, each of which an array of successive Vector3
  36068. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36069. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36070. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36071. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36072. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36073. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36074. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36075. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36076. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36077. * @returns the VertexData of the ribbon
  36078. */
  36079. VertexData.CreateRibbon = function (options) {
  36080. var pathArray = options.pathArray;
  36081. var closeArray = options.closeArray || false;
  36082. var closePath = options.closePath || false;
  36083. var invertUV = options.invertUV || false;
  36084. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36085. var offset = options.offset || defaultOffset;
  36086. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36087. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36088. var customUV = options.uvs;
  36089. var customColors = options.colors;
  36090. var positions = [];
  36091. var indices = [];
  36092. var normals = [];
  36093. var uvs = [];
  36094. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36095. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36096. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36097. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36098. var minlg; // minimal length among all paths from pathArray
  36099. var lg = []; // array of path lengths : nb of vertex per path
  36100. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36101. var p; // path iterator
  36102. var i; // point iterator
  36103. var j; // point iterator
  36104. // if single path in pathArray
  36105. if (pathArray.length < 2) {
  36106. var ar1 = [];
  36107. var ar2 = [];
  36108. for (i = 0; i < pathArray[0].length - offset; i++) {
  36109. ar1.push(pathArray[0][i]);
  36110. ar2.push(pathArray[0][i + offset]);
  36111. }
  36112. pathArray = [ar1, ar2];
  36113. }
  36114. // positions and horizontal distances (u)
  36115. var idc = 0;
  36116. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36117. var path;
  36118. var l;
  36119. minlg = pathArray[0].length;
  36120. var vectlg;
  36121. var dist;
  36122. for (p = 0; p < pathArray.length; p++) {
  36123. uTotalDistance[p] = 0;
  36124. us[p] = [0];
  36125. path = pathArray[p];
  36126. l = path.length;
  36127. minlg = (minlg < l) ? minlg : l;
  36128. j = 0;
  36129. while (j < l) {
  36130. positions.push(path[j].x, path[j].y, path[j].z);
  36131. if (j > 0) {
  36132. vectlg = path[j].subtract(path[j - 1]).length();
  36133. dist = vectlg + uTotalDistance[p];
  36134. us[p].push(dist);
  36135. uTotalDistance[p] = dist;
  36136. }
  36137. j++;
  36138. }
  36139. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36140. j--;
  36141. positions.push(path[0].x, path[0].y, path[0].z);
  36142. vectlg = path[j].subtract(path[0]).length();
  36143. dist = vectlg + uTotalDistance[p];
  36144. us[p].push(dist);
  36145. uTotalDistance[p] = dist;
  36146. }
  36147. lg[p] = l + closePathCorr;
  36148. idx[p] = idc;
  36149. idc += (l + closePathCorr);
  36150. }
  36151. // vertical distances (v)
  36152. var path1;
  36153. var path2;
  36154. var vertex1 = null;
  36155. var vertex2 = null;
  36156. for (i = 0; i < minlg + closePathCorr; i++) {
  36157. vTotalDistance[i] = 0;
  36158. vs[i] = [0];
  36159. for (p = 0; p < pathArray.length - 1; p++) {
  36160. path1 = pathArray[p];
  36161. path2 = pathArray[p + 1];
  36162. if (i === minlg) { // closePath
  36163. vertex1 = path1[0];
  36164. vertex2 = path2[0];
  36165. }
  36166. else {
  36167. vertex1 = path1[i];
  36168. vertex2 = path2[i];
  36169. }
  36170. vectlg = vertex2.subtract(vertex1).length();
  36171. dist = vectlg + vTotalDistance[i];
  36172. vs[i].push(dist);
  36173. vTotalDistance[i] = dist;
  36174. }
  36175. if (closeArray && vertex2 && vertex1) {
  36176. path1 = pathArray[p];
  36177. path2 = pathArray[0];
  36178. if (i === minlg) { // closePath
  36179. vertex2 = path2[0];
  36180. }
  36181. vectlg = vertex2.subtract(vertex1).length();
  36182. dist = vectlg + vTotalDistance[i];
  36183. vTotalDistance[i] = dist;
  36184. }
  36185. }
  36186. // uvs
  36187. var u;
  36188. var v;
  36189. if (customUV) {
  36190. for (p = 0; p < customUV.length; p++) {
  36191. uvs.push(customUV[p].x, customUV[p].y);
  36192. }
  36193. }
  36194. else {
  36195. for (p = 0; p < pathArray.length; p++) {
  36196. for (i = 0; i < minlg + closePathCorr; i++) {
  36197. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36198. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36199. if (invertUV) {
  36200. uvs.push(v, u);
  36201. }
  36202. else {
  36203. uvs.push(u, v);
  36204. }
  36205. }
  36206. }
  36207. }
  36208. // indices
  36209. p = 0; // path index
  36210. var pi = 0; // positions array index
  36211. var l1 = lg[p] - 1; // path1 length
  36212. var l2 = lg[p + 1] - 1; // path2 length
  36213. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36214. var shft = idx[1] - idx[0]; // shift
  36215. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36216. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36217. // 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
  36218. indices.push(pi, pi + shft, pi + 1);
  36219. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36220. pi += 1;
  36221. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36222. p++;
  36223. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36224. shft = idx[0] - idx[p];
  36225. l1 = lg[p] - 1;
  36226. l2 = lg[0] - 1;
  36227. }
  36228. else {
  36229. shft = idx[p + 1] - idx[p];
  36230. l1 = lg[p] - 1;
  36231. l2 = lg[p + 1] - 1;
  36232. }
  36233. pi = idx[p];
  36234. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36235. }
  36236. }
  36237. // normals
  36238. VertexData.ComputeNormals(positions, indices, normals);
  36239. if (closePath) { // update both the first and last vertex normals to their average value
  36240. var indexFirst = 0;
  36241. var indexLast = 0;
  36242. for (p = 0; p < pathArray.length; p++) {
  36243. indexFirst = idx[p] * 3;
  36244. if (p + 1 < pathArray.length) {
  36245. indexLast = (idx[p + 1] - 1) * 3;
  36246. }
  36247. else {
  36248. indexLast = normals.length - 3;
  36249. }
  36250. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36251. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36252. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36253. normals[indexLast] = normals[indexFirst];
  36254. normals[indexLast + 1] = normals[indexFirst + 1];
  36255. normals[indexLast + 2] = normals[indexFirst + 2];
  36256. }
  36257. }
  36258. // sides
  36259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36260. // Colors
  36261. var colors = null;
  36262. if (customColors) {
  36263. colors = new Float32Array(customColors.length * 4);
  36264. for (var c = 0; c < customColors.length; c++) {
  36265. colors[c * 4] = customColors[c].r;
  36266. colors[c * 4 + 1] = customColors[c].g;
  36267. colors[c * 4 + 2] = customColors[c].b;
  36268. colors[c * 4 + 3] = customColors[c].a;
  36269. }
  36270. }
  36271. // Result
  36272. var vertexData = new VertexData();
  36273. var positions32 = new Float32Array(positions);
  36274. var normals32 = new Float32Array(normals);
  36275. var uvs32 = new Float32Array(uvs);
  36276. vertexData.indices = indices;
  36277. vertexData.positions = positions32;
  36278. vertexData.normals = normals32;
  36279. vertexData.uvs = uvs32;
  36280. if (colors) {
  36281. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36282. }
  36283. if (closePath) {
  36284. vertexData._idx = idx;
  36285. }
  36286. return vertexData;
  36287. };
  36288. /**
  36289. * Creates the VertexData for a box
  36290. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36291. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36292. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36293. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36294. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36295. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36296. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36297. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36298. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36299. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36300. * @returns the VertexData of the box
  36301. */
  36302. VertexData.CreateBox = function (options) {
  36303. var normalsSource = [
  36304. new BABYLON.Vector3(0, 0, 1),
  36305. new BABYLON.Vector3(0, 0, -1),
  36306. new BABYLON.Vector3(1, 0, 0),
  36307. new BABYLON.Vector3(-1, 0, 0),
  36308. new BABYLON.Vector3(0, 1, 0),
  36309. new BABYLON.Vector3(0, -1, 0)
  36310. ];
  36311. var indices = [];
  36312. var positions = [];
  36313. var normals = [];
  36314. var uvs = [];
  36315. var width = options.width || options.size || 1;
  36316. var height = options.height || options.size || 1;
  36317. var depth = options.depth || options.size || 1;
  36318. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36319. var faceUV = options.faceUV || new Array(6);
  36320. var faceColors = options.faceColors;
  36321. var colors = [];
  36322. // default face colors and UV if undefined
  36323. for (var f = 0; f < 6; f++) {
  36324. if (faceUV[f] === undefined) {
  36325. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36326. }
  36327. if (faceColors && faceColors[f] === undefined) {
  36328. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36329. }
  36330. }
  36331. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36332. // Create each face in turn.
  36333. for (var index = 0; index < normalsSource.length; index++) {
  36334. var normal = normalsSource[index];
  36335. // Get two vectors perpendicular to the face normal and to each other.
  36336. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36337. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36338. // Six indices (two triangles) per face.
  36339. var verticesLength = positions.length / 3;
  36340. indices.push(verticesLength);
  36341. indices.push(verticesLength + 1);
  36342. indices.push(verticesLength + 2);
  36343. indices.push(verticesLength);
  36344. indices.push(verticesLength + 2);
  36345. indices.push(verticesLength + 3);
  36346. // Four vertices per face.
  36347. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36348. positions.push(vertex.x, vertex.y, vertex.z);
  36349. normals.push(normal.x, normal.y, normal.z);
  36350. uvs.push(faceUV[index].z, faceUV[index].w);
  36351. if (faceColors) {
  36352. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36353. }
  36354. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36355. positions.push(vertex.x, vertex.y, vertex.z);
  36356. normals.push(normal.x, normal.y, normal.z);
  36357. uvs.push(faceUV[index].x, faceUV[index].w);
  36358. if (faceColors) {
  36359. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36360. }
  36361. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36362. positions.push(vertex.x, vertex.y, vertex.z);
  36363. normals.push(normal.x, normal.y, normal.z);
  36364. uvs.push(faceUV[index].x, faceUV[index].y);
  36365. if (faceColors) {
  36366. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36367. }
  36368. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36369. positions.push(vertex.x, vertex.y, vertex.z);
  36370. normals.push(normal.x, normal.y, normal.z);
  36371. uvs.push(faceUV[index].z, faceUV[index].y);
  36372. if (faceColors) {
  36373. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36374. }
  36375. }
  36376. // sides
  36377. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36378. // Result
  36379. var vertexData = new VertexData();
  36380. vertexData.indices = indices;
  36381. vertexData.positions = positions;
  36382. vertexData.normals = normals;
  36383. vertexData.uvs = uvs;
  36384. if (faceColors) {
  36385. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36386. vertexData.colors = totalColors;
  36387. }
  36388. return vertexData;
  36389. };
  36390. /**
  36391. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36392. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36393. * * segments sets the number of horizontal strips optional, default 32
  36394. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36395. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36396. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36397. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36398. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36399. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36400. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36401. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36402. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36403. * @returns the VertexData of the ellipsoid
  36404. */
  36405. VertexData.CreateSphere = function (options) {
  36406. var segments = options.segments || 32;
  36407. var diameterX = options.diameterX || options.diameter || 1;
  36408. var diameterY = options.diameterY || options.diameter || 1;
  36409. var diameterZ = options.diameterZ || options.diameter || 1;
  36410. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36411. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36413. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36414. var totalZRotationSteps = 2 + segments;
  36415. var totalYRotationSteps = 2 * totalZRotationSteps;
  36416. var indices = [];
  36417. var positions = [];
  36418. var normals = [];
  36419. var uvs = [];
  36420. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36421. var normalizedZ = zRotationStep / totalZRotationSteps;
  36422. var angleZ = normalizedZ * Math.PI * slice;
  36423. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36424. var normalizedY = yRotationStep / totalYRotationSteps;
  36425. var angleY = normalizedY * Math.PI * 2 * arc;
  36426. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36427. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36428. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36429. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36430. var vertex = complete.multiply(radius);
  36431. var normal = complete.divide(radius).normalize();
  36432. positions.push(vertex.x, vertex.y, vertex.z);
  36433. normals.push(normal.x, normal.y, normal.z);
  36434. uvs.push(normalizedY, normalizedZ);
  36435. }
  36436. if (zRotationStep > 0) {
  36437. var verticesCount = positions.length / 3;
  36438. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36439. indices.push((firstIndex));
  36440. indices.push((firstIndex + 1));
  36441. indices.push(firstIndex + totalYRotationSteps + 1);
  36442. indices.push((firstIndex + totalYRotationSteps + 1));
  36443. indices.push((firstIndex + 1));
  36444. indices.push((firstIndex + totalYRotationSteps + 2));
  36445. }
  36446. }
  36447. }
  36448. // Sides
  36449. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36450. // Result
  36451. var vertexData = new VertexData();
  36452. vertexData.indices = indices;
  36453. vertexData.positions = positions;
  36454. vertexData.normals = normals;
  36455. vertexData.uvs = uvs;
  36456. return vertexData;
  36457. };
  36458. /**
  36459. * Creates the VertexData for a cylinder, cone or prism
  36460. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36461. * * height sets the height (y direction) of the cylinder, optional, default 2
  36462. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36463. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36464. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36465. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36466. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36467. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36468. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36469. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36470. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36471. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36472. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36473. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36474. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36475. * @returns the VertexData of the cylinder, cone or prism
  36476. */
  36477. VertexData.CreateCylinder = function (options) {
  36478. var height = options.height || 2;
  36479. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36480. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36481. var tessellation = options.tessellation || 24;
  36482. var subdivisions = options.subdivisions || 1;
  36483. var hasRings = options.hasRings ? true : false;
  36484. var enclose = options.enclose ? true : false;
  36485. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36486. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36487. var faceUV = options.faceUV || new Array(3);
  36488. var faceColors = options.faceColors;
  36489. // default face colors and UV if undefined
  36490. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36491. var ringNb = (hasRings) ? subdivisions : 1;
  36492. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36493. var f;
  36494. for (f = 0; f < surfaceNb; f++) {
  36495. if (faceColors && faceColors[f] === undefined) {
  36496. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36497. }
  36498. }
  36499. for (f = 0; f < surfaceNb; f++) {
  36500. if (faceUV && faceUV[f] === undefined) {
  36501. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36502. }
  36503. }
  36504. var indices = new Array();
  36505. var positions = new Array();
  36506. var normals = new Array();
  36507. var uvs = new Array();
  36508. var colors = new Array();
  36509. var angle_step = Math.PI * 2 * arc / tessellation;
  36510. var angle;
  36511. var h;
  36512. var radius;
  36513. var tan = (diameterBottom - diameterTop) / 2 / height;
  36514. var ringVertex = BABYLON.Vector3.Zero();
  36515. var ringNormal = BABYLON.Vector3.Zero();
  36516. var ringFirstVertex = BABYLON.Vector3.Zero();
  36517. var ringFirstNormal = BABYLON.Vector3.Zero();
  36518. var quadNormal = BABYLON.Vector3.Zero();
  36519. var Y = BABYLON.Axis.Y;
  36520. // positions, normals, uvs
  36521. var i;
  36522. var j;
  36523. var r;
  36524. var ringIdx = 1;
  36525. var s = 1; // surface index
  36526. var cs = 0;
  36527. var v = 0;
  36528. for (i = 0; i <= subdivisions; i++) {
  36529. h = i / subdivisions;
  36530. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36531. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36532. for (r = 0; r < ringIdx; r++) {
  36533. if (hasRings) {
  36534. s += r;
  36535. }
  36536. if (enclose) {
  36537. s += 2 * r;
  36538. }
  36539. for (j = 0; j <= tessellation; j++) {
  36540. angle = j * angle_step;
  36541. // position
  36542. ringVertex.x = Math.cos(-angle) * radius;
  36543. ringVertex.y = -height / 2 + h * height;
  36544. ringVertex.z = Math.sin(-angle) * radius;
  36545. // normal
  36546. if (diameterTop === 0 && i === subdivisions) {
  36547. // if no top cap, reuse former normals
  36548. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36549. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36550. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36551. }
  36552. else {
  36553. ringNormal.x = ringVertex.x;
  36554. ringNormal.z = ringVertex.z;
  36555. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36556. ringNormal.normalize();
  36557. }
  36558. // keep first ring vertex values for enclose
  36559. if (j === 0) {
  36560. ringFirstVertex.copyFrom(ringVertex);
  36561. ringFirstNormal.copyFrom(ringNormal);
  36562. }
  36563. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36564. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36565. if (hasRings) {
  36566. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36567. }
  36568. else {
  36569. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36570. }
  36571. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36572. if (faceColors) {
  36573. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36574. }
  36575. }
  36576. // if enclose, add four vertices and their dedicated normals
  36577. if (arc !== 1 && enclose) {
  36578. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36579. positions.push(0, ringVertex.y, 0);
  36580. positions.push(0, ringVertex.y, 0);
  36581. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36582. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36583. quadNormal.normalize();
  36584. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36585. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36586. quadNormal.normalize();
  36587. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36588. if (hasRings) {
  36589. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36590. }
  36591. else {
  36592. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36593. }
  36594. uvs.push(faceUV[s + 1].x, v);
  36595. uvs.push(faceUV[s + 1].z, v);
  36596. if (hasRings) {
  36597. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36598. }
  36599. else {
  36600. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36601. }
  36602. uvs.push(faceUV[s + 2].x, v);
  36603. uvs.push(faceUV[s + 2].z, v);
  36604. if (faceColors) {
  36605. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36606. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36607. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36608. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36609. }
  36610. }
  36611. if (cs !== s) {
  36612. cs = s;
  36613. }
  36614. }
  36615. }
  36616. // indices
  36617. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36618. var s;
  36619. i = 0;
  36620. for (s = 0; s < subdivisions; s++) {
  36621. var i0 = 0;
  36622. var i1 = 0;
  36623. var i2 = 0;
  36624. var i3 = 0;
  36625. for (j = 0; j < tessellation; j++) {
  36626. i0 = i * (e + 1) + j;
  36627. i1 = (i + 1) * (e + 1) + j;
  36628. i2 = i * (e + 1) + (j + 1);
  36629. i3 = (i + 1) * (e + 1) + (j + 1);
  36630. indices.push(i0, i1, i2);
  36631. indices.push(i3, i2, i1);
  36632. }
  36633. if (arc !== 1 && enclose) { // if enclose, add two quads
  36634. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36635. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36636. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36637. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36638. }
  36639. i = (hasRings) ? (i + 2) : (i + 1);
  36640. }
  36641. // Caps
  36642. var createCylinderCap = function (isTop) {
  36643. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36644. if (radius === 0) {
  36645. return;
  36646. }
  36647. // Cap positions, normals & uvs
  36648. var angle;
  36649. var circleVector;
  36650. var i;
  36651. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36652. var c = null;
  36653. if (faceColors) {
  36654. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36655. }
  36656. // cap center
  36657. var vbase = positions.length / 3;
  36658. var offset = isTop ? height / 2 : -height / 2;
  36659. var center = new BABYLON.Vector3(0, offset, 0);
  36660. positions.push(center.x, center.y, center.z);
  36661. normals.push(0, isTop ? 1 : -1, 0);
  36662. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36663. if (c) {
  36664. colors.push(c.r, c.g, c.b, c.a);
  36665. }
  36666. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36667. for (i = 0; i <= tessellation; i++) {
  36668. angle = Math.PI * 2 * i * arc / tessellation;
  36669. var cos = Math.cos(-angle);
  36670. var sin = Math.sin(-angle);
  36671. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36672. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36673. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36674. normals.push(0, isTop ? 1 : -1, 0);
  36675. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36676. if (c) {
  36677. colors.push(c.r, c.g, c.b, c.a);
  36678. }
  36679. }
  36680. // Cap indices
  36681. for (i = 0; i < tessellation; i++) {
  36682. if (!isTop) {
  36683. indices.push(vbase);
  36684. indices.push(vbase + (i + 1));
  36685. indices.push(vbase + (i + 2));
  36686. }
  36687. else {
  36688. indices.push(vbase);
  36689. indices.push(vbase + (i + 2));
  36690. indices.push(vbase + (i + 1));
  36691. }
  36692. }
  36693. };
  36694. // add caps to geometry
  36695. createCylinderCap(false);
  36696. createCylinderCap(true);
  36697. // Sides
  36698. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36699. var vertexData = new VertexData();
  36700. vertexData.indices = indices;
  36701. vertexData.positions = positions;
  36702. vertexData.normals = normals;
  36703. vertexData.uvs = uvs;
  36704. if (faceColors) {
  36705. vertexData.colors = colors;
  36706. }
  36707. return vertexData;
  36708. };
  36709. /**
  36710. * Creates the VertexData for a torus
  36711. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36712. * * diameter the diameter of the torus, optional default 1
  36713. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36714. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36715. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36716. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36717. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36718. * @returns the VertexData of the torus
  36719. */
  36720. VertexData.CreateTorus = function (options) {
  36721. var indices = [];
  36722. var positions = [];
  36723. var normals = [];
  36724. var uvs = [];
  36725. var diameter = options.diameter || 1;
  36726. var thickness = options.thickness || 0.5;
  36727. var tessellation = options.tessellation || 16;
  36728. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36729. var stride = tessellation + 1;
  36730. for (var i = 0; i <= tessellation; i++) {
  36731. var u = i / tessellation;
  36732. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36733. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36734. for (var j = 0; j <= tessellation; j++) {
  36735. var v = 1 - j / tessellation;
  36736. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36737. var dx = Math.cos(innerAngle);
  36738. var dy = Math.sin(innerAngle);
  36739. // Create a vertex.
  36740. var normal = new BABYLON.Vector3(dx, dy, 0);
  36741. var position = normal.scale(thickness / 2);
  36742. var textureCoordinate = new BABYLON.Vector2(u, v);
  36743. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36744. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36745. positions.push(position.x, position.y, position.z);
  36746. normals.push(normal.x, normal.y, normal.z);
  36747. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36748. // And create indices for two triangles.
  36749. var nextI = (i + 1) % stride;
  36750. var nextJ = (j + 1) % stride;
  36751. indices.push(i * stride + j);
  36752. indices.push(i * stride + nextJ);
  36753. indices.push(nextI * stride + j);
  36754. indices.push(i * stride + nextJ);
  36755. indices.push(nextI * stride + nextJ);
  36756. indices.push(nextI * stride + j);
  36757. }
  36758. }
  36759. // Sides
  36760. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36761. // Result
  36762. var vertexData = new VertexData();
  36763. vertexData.indices = indices;
  36764. vertexData.positions = positions;
  36765. vertexData.normals = normals;
  36766. vertexData.uvs = uvs;
  36767. return vertexData;
  36768. };
  36769. /**
  36770. * Creates the VertexData of the LineSystem
  36771. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36772. * - lines an array of lines, each line being an array of successive Vector3
  36773. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36774. * @returns the VertexData of the LineSystem
  36775. */
  36776. VertexData.CreateLineSystem = function (options) {
  36777. var indices = [];
  36778. var positions = [];
  36779. var lines = options.lines;
  36780. var colors = options.colors;
  36781. var vertexColors = [];
  36782. var idx = 0;
  36783. for (var l = 0; l < lines.length; l++) {
  36784. var points = lines[l];
  36785. for (var index = 0; index < points.length; index++) {
  36786. positions.push(points[index].x, points[index].y, points[index].z);
  36787. if (colors) {
  36788. var color = colors[l];
  36789. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36790. }
  36791. if (index > 0) {
  36792. indices.push(idx - 1);
  36793. indices.push(idx);
  36794. }
  36795. idx++;
  36796. }
  36797. }
  36798. var vertexData = new VertexData();
  36799. vertexData.indices = indices;
  36800. vertexData.positions = positions;
  36801. if (colors) {
  36802. vertexData.colors = vertexColors;
  36803. }
  36804. return vertexData;
  36805. };
  36806. /**
  36807. * Create the VertexData for a DashedLines
  36808. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36809. * - points an array successive Vector3
  36810. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36811. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36812. * - dashNb the intended total number of dashes, optional, default 200
  36813. * @returns the VertexData for the DashedLines
  36814. */
  36815. VertexData.CreateDashedLines = function (options) {
  36816. var dashSize = options.dashSize || 3;
  36817. var gapSize = options.gapSize || 1;
  36818. var dashNb = options.dashNb || 200;
  36819. var points = options.points;
  36820. var positions = new Array();
  36821. var indices = new Array();
  36822. var curvect = BABYLON.Vector3.Zero();
  36823. var lg = 0;
  36824. var nb = 0;
  36825. var shft = 0;
  36826. var dashshft = 0;
  36827. var curshft = 0;
  36828. var idx = 0;
  36829. var i = 0;
  36830. for (i = 0; i < points.length - 1; i++) {
  36831. points[i + 1].subtractToRef(points[i], curvect);
  36832. lg += curvect.length();
  36833. }
  36834. shft = lg / dashNb;
  36835. dashshft = dashSize * shft / (dashSize + gapSize);
  36836. for (i = 0; i < points.length - 1; i++) {
  36837. points[i + 1].subtractToRef(points[i], curvect);
  36838. nb = Math.floor(curvect.length() / shft);
  36839. curvect.normalize();
  36840. for (var j = 0; j < nb; j++) {
  36841. curshft = shft * j;
  36842. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36843. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36844. indices.push(idx, idx + 1);
  36845. idx += 2;
  36846. }
  36847. }
  36848. // Result
  36849. var vertexData = new VertexData();
  36850. vertexData.positions = positions;
  36851. vertexData.indices = indices;
  36852. return vertexData;
  36853. };
  36854. /**
  36855. * Creates the VertexData for a Ground
  36856. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36857. * - width the width (x direction) of the ground, optional, default 1
  36858. * - height the height (z direction) of the ground, optional, default 1
  36859. * - subdivisions the number of subdivisions per side, optional, default 1
  36860. * @returns the VertexData of the Ground
  36861. */
  36862. VertexData.CreateGround = function (options) {
  36863. var indices = [];
  36864. var positions = [];
  36865. var normals = [];
  36866. var uvs = [];
  36867. var row, col;
  36868. var width = options.width || 1;
  36869. var height = options.height || 1;
  36870. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36871. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36872. for (row = 0; row <= subdivisionsY; row++) {
  36873. for (col = 0; col <= subdivisionsX; col++) {
  36874. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36875. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36876. positions.push(position.x, position.y, position.z);
  36877. normals.push(normal.x, normal.y, normal.z);
  36878. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36879. }
  36880. }
  36881. for (row = 0; row < subdivisionsY; row++) {
  36882. for (col = 0; col < subdivisionsX; col++) {
  36883. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36884. indices.push(col + 1 + row * (subdivisionsX + 1));
  36885. indices.push(col + row * (subdivisionsX + 1));
  36886. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36887. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36888. indices.push(col + row * (subdivisionsX + 1));
  36889. }
  36890. }
  36891. // Result
  36892. var vertexData = new VertexData();
  36893. vertexData.indices = indices;
  36894. vertexData.positions = positions;
  36895. vertexData.normals = normals;
  36896. vertexData.uvs = uvs;
  36897. return vertexData;
  36898. };
  36899. /**
  36900. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36901. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36902. * * xmin the ground minimum X coordinate, optional, default -1
  36903. * * zmin the ground minimum Z coordinate, optional, default -1
  36904. * * xmax the ground maximum X coordinate, optional, default 1
  36905. * * zmax the ground maximum Z coordinate, optional, default 1
  36906. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  36907. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  36908. * @returns the VertexData of the TiledGround
  36909. */
  36910. VertexData.CreateTiledGround = function (options) {
  36911. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36912. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36913. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36914. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36915. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36916. var precision = options.precision || { w: 1, h: 1 };
  36917. var indices = new Array();
  36918. var positions = new Array();
  36919. var normals = new Array();
  36920. var uvs = new Array();
  36921. var row, col, tileRow, tileCol;
  36922. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36923. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36924. precision.w = (precision.w < 1) ? 1 : precision.w;
  36925. precision.h = (precision.h < 1) ? 1 : precision.h;
  36926. var tileSize = {
  36927. 'w': (xmax - xmin) / subdivisions.w,
  36928. 'h': (zmax - zmin) / subdivisions.h
  36929. };
  36930. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36931. // Indices
  36932. var base = positions.length / 3;
  36933. var rowLength = precision.w + 1;
  36934. for (row = 0; row < precision.h; row++) {
  36935. for (col = 0; col < precision.w; col++) {
  36936. var square = [
  36937. base + col + row * rowLength,
  36938. base + (col + 1) + row * rowLength,
  36939. base + (col + 1) + (row + 1) * rowLength,
  36940. base + col + (row + 1) * rowLength
  36941. ];
  36942. indices.push(square[1]);
  36943. indices.push(square[2]);
  36944. indices.push(square[3]);
  36945. indices.push(square[0]);
  36946. indices.push(square[1]);
  36947. indices.push(square[3]);
  36948. }
  36949. }
  36950. // Position, normals and uvs
  36951. var position = BABYLON.Vector3.Zero();
  36952. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36953. for (row = 0; row <= precision.h; row++) {
  36954. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36955. for (col = 0; col <= precision.w; col++) {
  36956. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36957. position.y = 0;
  36958. positions.push(position.x, position.y, position.z);
  36959. normals.push(normal.x, normal.y, normal.z);
  36960. uvs.push(col / precision.w, row / precision.h);
  36961. }
  36962. }
  36963. }
  36964. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36965. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36966. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36967. }
  36968. }
  36969. // Result
  36970. var vertexData = new VertexData();
  36971. vertexData.indices = indices;
  36972. vertexData.positions = positions;
  36973. vertexData.normals = normals;
  36974. vertexData.uvs = uvs;
  36975. return vertexData;
  36976. };
  36977. /**
  36978. * Creates the VertexData of the Ground designed from a heightmap
  36979. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  36980. * * width the width (x direction) of the ground
  36981. * * height the height (z direction) of the ground
  36982. * * subdivisions the number of subdivisions per side
  36983. * * minHeight the minimum altitude on the ground, optional, default 0
  36984. * * maxHeight the maximum altitude on the ground, optional default 1
  36985. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  36986. * * buffer the array holding the image color data
  36987. * * bufferWidth the width of image
  36988. * * bufferHeight the height of image
  36989. * @returns the VertexData of the Ground designed from a heightmap
  36990. */
  36991. VertexData.CreateGroundFromHeightMap = function (options) {
  36992. var indices = [];
  36993. var positions = [];
  36994. var normals = [];
  36995. var uvs = [];
  36996. var row, col;
  36997. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36998. // Vertices
  36999. for (row = 0; row <= options.subdivisions; row++) {
  37000. for (col = 0; col <= options.subdivisions; col++) {
  37001. 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));
  37002. // Compute height
  37003. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37004. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37005. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37006. var r = options.buffer[pos] / 255.0;
  37007. var g = options.buffer[pos + 1] / 255.0;
  37008. var b = options.buffer[pos + 2] / 255.0;
  37009. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37010. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37011. // Add vertex
  37012. positions.push(position.x, position.y, position.z);
  37013. normals.push(0, 0, 0);
  37014. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37015. }
  37016. }
  37017. // Indices
  37018. for (row = 0; row < options.subdivisions; row++) {
  37019. for (col = 0; col < options.subdivisions; col++) {
  37020. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37021. indices.push(col + 1 + row * (options.subdivisions + 1));
  37022. indices.push(col + row * (options.subdivisions + 1));
  37023. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37024. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37025. indices.push(col + row * (options.subdivisions + 1));
  37026. }
  37027. }
  37028. // Normals
  37029. VertexData.ComputeNormals(positions, indices, normals);
  37030. // Result
  37031. var vertexData = new VertexData();
  37032. vertexData.indices = indices;
  37033. vertexData.positions = positions;
  37034. vertexData.normals = normals;
  37035. vertexData.uvs = uvs;
  37036. return vertexData;
  37037. };
  37038. /**
  37039. * Creates the VertexData for a Plane
  37040. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37041. * * size sets the width and height of the plane to the value of size, optional default 1
  37042. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37043. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37044. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37045. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37046. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37047. * @returns the VertexData of the box
  37048. */
  37049. VertexData.CreatePlane = function (options) {
  37050. var indices = [];
  37051. var positions = [];
  37052. var normals = [];
  37053. var uvs = [];
  37054. var width = options.width || options.size || 1;
  37055. var height = options.height || options.size || 1;
  37056. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37057. // Vertices
  37058. var halfWidth = width / 2.0;
  37059. var halfHeight = height / 2.0;
  37060. positions.push(-halfWidth, -halfHeight, 0);
  37061. normals.push(0, 0, -1.0);
  37062. uvs.push(0.0, 0.0);
  37063. positions.push(halfWidth, -halfHeight, 0);
  37064. normals.push(0, 0, -1.0);
  37065. uvs.push(1.0, 0.0);
  37066. positions.push(halfWidth, halfHeight, 0);
  37067. normals.push(0, 0, -1.0);
  37068. uvs.push(1.0, 1.0);
  37069. positions.push(-halfWidth, halfHeight, 0);
  37070. normals.push(0, 0, -1.0);
  37071. uvs.push(0.0, 1.0);
  37072. // Indices
  37073. indices.push(0);
  37074. indices.push(1);
  37075. indices.push(2);
  37076. indices.push(0);
  37077. indices.push(2);
  37078. indices.push(3);
  37079. // Sides
  37080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37081. // Result
  37082. var vertexData = new VertexData();
  37083. vertexData.indices = indices;
  37084. vertexData.positions = positions;
  37085. vertexData.normals = normals;
  37086. vertexData.uvs = uvs;
  37087. return vertexData;
  37088. };
  37089. /**
  37090. * Creates the VertexData of the Disc or regular Polygon
  37091. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37092. * * radius the radius of the disc, optional default 0.5
  37093. * * tessellation the number of polygon sides, optional, default 64
  37094. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37095. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37096. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37097. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37098. * @returns the VertexData of the box
  37099. */
  37100. VertexData.CreateDisc = function (options) {
  37101. var positions = new Array();
  37102. var indices = new Array();
  37103. var normals = new Array();
  37104. var uvs = new Array();
  37105. var radius = options.radius || 0.5;
  37106. var tessellation = options.tessellation || 64;
  37107. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37109. // positions and uvs
  37110. positions.push(0, 0, 0); // disc center first
  37111. uvs.push(0.5, 0.5);
  37112. var theta = Math.PI * 2 * arc;
  37113. var step = theta / tessellation;
  37114. for (var a = 0; a < theta; a += step) {
  37115. var x = Math.cos(a);
  37116. var y = Math.sin(a);
  37117. var u = (x + 1) / 2;
  37118. var v = (1 - y) / 2;
  37119. positions.push(radius * x, radius * y, 0);
  37120. uvs.push(u, v);
  37121. }
  37122. if (arc === 1) {
  37123. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37124. uvs.push(uvs[2], uvs[3]);
  37125. }
  37126. //indices
  37127. var vertexNb = positions.length / 3;
  37128. for (var i = 1; i < vertexNb - 1; i++) {
  37129. indices.push(i + 1, 0, i);
  37130. }
  37131. // result
  37132. VertexData.ComputeNormals(positions, indices, normals);
  37133. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37134. var vertexData = new VertexData();
  37135. vertexData.indices = indices;
  37136. vertexData.positions = positions;
  37137. vertexData.normals = normals;
  37138. vertexData.uvs = uvs;
  37139. return vertexData;
  37140. };
  37141. /**
  37142. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37143. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37144. * @param polygon a mesh built from polygonTriangulation.build()
  37145. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37146. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37147. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37148. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37149. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37150. * @returns the VertexData of the Polygon
  37151. */
  37152. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37153. var faceUV = fUV || new Array(3);
  37154. var faceColors = fColors;
  37155. var colors = [];
  37156. // default face colors and UV if undefined
  37157. for (var f = 0; f < 3; f++) {
  37158. if (faceUV[f] === undefined) {
  37159. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37160. }
  37161. if (faceColors && faceColors[f] === undefined) {
  37162. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37163. }
  37164. }
  37165. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37166. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37167. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37168. var indices = polygon.getIndices();
  37169. // set face colours and textures
  37170. var idx = 0;
  37171. var face = 0;
  37172. for (var index = 0; index < normals.length; index += 3) {
  37173. //Edge Face no. 1
  37174. if (Math.abs(normals[index + 1]) < 0.001) {
  37175. face = 1;
  37176. }
  37177. //Top Face no. 0
  37178. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37179. face = 0;
  37180. }
  37181. //Bottom Face no. 2
  37182. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37183. face = 2;
  37184. }
  37185. idx = index / 3;
  37186. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37187. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37188. if (faceColors) {
  37189. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37190. }
  37191. }
  37192. // sides
  37193. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37194. // Result
  37195. var vertexData = new VertexData();
  37196. vertexData.indices = indices;
  37197. vertexData.positions = positions;
  37198. vertexData.normals = normals;
  37199. vertexData.uvs = uvs;
  37200. if (faceColors) {
  37201. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37202. vertexData.colors = totalColors;
  37203. }
  37204. return vertexData;
  37205. };
  37206. /**
  37207. * Creates the VertexData of the IcoSphere
  37208. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37209. * * radius the radius of the IcoSphere, optional default 1
  37210. * * radiusX allows stretching in the x direction, optional, default radius
  37211. * * radiusY allows stretching in the y direction, optional, default radius
  37212. * * radiusZ allows stretching in the z direction, optional, default radius
  37213. * * flat when true creates a flat shaded mesh, optional, default true
  37214. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37215. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37216. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37217. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37218. * @returns the VertexData of the IcoSphere
  37219. */
  37220. VertexData.CreateIcoSphere = function (options) {
  37221. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37222. var radius = options.radius || 1;
  37223. var flat = (options.flat === undefined) ? true : options.flat;
  37224. var subdivisions = options.subdivisions || 4;
  37225. var radiusX = options.radiusX || radius;
  37226. var radiusY = options.radiusY || radius;
  37227. var radiusZ = options.radiusZ || radius;
  37228. var t = (1 + Math.sqrt(5)) / 2;
  37229. // 12 vertex x,y,z
  37230. var ico_vertices = [
  37231. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37232. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37233. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37234. ];
  37235. // index of 3 vertex makes a face of icopshere
  37236. var ico_indices = [
  37237. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37238. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37239. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37240. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37241. ];
  37242. // vertex for uv have aliased position, not for UV
  37243. var vertices_unalias_id = [
  37244. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37245. // vertex alias
  37246. 0,
  37247. 2,
  37248. 3,
  37249. 3,
  37250. 3,
  37251. 4,
  37252. 7,
  37253. 8,
  37254. 9,
  37255. 9,
  37256. 10,
  37257. 11 // 23: B + 12
  37258. ];
  37259. // uv as integer step (not pixels !)
  37260. var ico_vertexuv = [
  37261. 5, 1, 3, 1, 6, 4, 0, 0,
  37262. 5, 3, 4, 2, 2, 2, 4, 0,
  37263. 2, 0, 1, 1, 6, 0, 6, 2,
  37264. // vertex alias (for same vertex on different faces)
  37265. 0, 4,
  37266. 3, 3,
  37267. 4, 4,
  37268. 3, 1,
  37269. 4, 2,
  37270. 4, 4,
  37271. 0, 2,
  37272. 1, 1,
  37273. 2, 2,
  37274. 3, 3,
  37275. 1, 3,
  37276. 2, 4 // 23: B + 12
  37277. ];
  37278. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37279. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37280. // First island of uv mapping
  37281. // v = 4h 3+ 2
  37282. // v = 3h 9+ 4
  37283. // v = 2h 9+ 5 B
  37284. // v = 1h 9 1 0
  37285. // v = 0h 3 8 7 A
  37286. // u = 0 1 2 3 4 5 6 *a
  37287. // Second island of uv mapping
  37288. // v = 4h 0+ B+ 4+
  37289. // v = 3h A+ 2+
  37290. // v = 2h 7+ 6 3+
  37291. // v = 1h 8+ 3+
  37292. // v = 0h
  37293. // u = 0 1 2 3 4 5 6 *a
  37294. // Face layout on texture UV mapping
  37295. // ============
  37296. // \ 4 /\ 16 / ======
  37297. // \ / \ / /\ 11 /
  37298. // \/ 7 \/ / \ /
  37299. // ======= / 10 \/
  37300. // /\ 17 /\ =======
  37301. // / \ / \ \ 15 /\
  37302. // / 8 \/ 12 \ \ / \
  37303. // ============ \/ 6 \
  37304. // \ 18 /\ ============
  37305. // \ / \ \ 5 /\ 0 /
  37306. // \/ 13 \ \ / \ /
  37307. // ======= \/ 1 \/
  37308. // =============
  37309. // /\ 19 /\ 2 /\
  37310. // / \ / \ / \
  37311. // / 14 \/ 9 \/ 3 \
  37312. // ===================
  37313. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37314. var ustep = 138 / 1024;
  37315. var vstep = 239 / 1024;
  37316. var uoffset = 60 / 1024;
  37317. var voffset = 26 / 1024;
  37318. // Second island should have margin, not to touch the first island
  37319. // avoid any borderline artefact in pixel rounding
  37320. var island_u_offset = -40 / 1024;
  37321. var island_v_offset = +20 / 1024;
  37322. // face is either island 0 or 1 :
  37323. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37324. var island = [
  37325. 0, 0, 0, 0, 1,
  37326. 0, 0, 1, 1, 0,
  37327. 0, 0, 1, 1, 0,
  37328. 0, 1, 1, 1, 0 // 15 - 19
  37329. ];
  37330. var indices = new Array();
  37331. var positions = new Array();
  37332. var normals = new Array();
  37333. var uvs = new Array();
  37334. var current_indice = 0;
  37335. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37336. var face_vertex_pos = new Array(3);
  37337. var face_vertex_uv = new Array(3);
  37338. var v012;
  37339. for (v012 = 0; v012 < 3; v012++) {
  37340. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37341. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37342. }
  37343. // create all with normals
  37344. for (var face = 0; face < 20; face++) {
  37345. // 3 vertex per face
  37346. for (v012 = 0; v012 < 3; v012++) {
  37347. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37348. var v_id = ico_indices[3 * face + v012];
  37349. // vertex have 3D position (x,y,z)
  37350. 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]);
  37351. // Normalize to get normal, then scale to radius
  37352. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37353. // uv Coordinates from vertex ID
  37354. 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);
  37355. }
  37356. // Subdivide the face (interpolate pos, norm, uv)
  37357. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37358. // - norm is linear interpolation of vertex corner normal
  37359. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37360. // - uv is linear interpolation
  37361. //
  37362. // Topology is as below for sub-divide by 2
  37363. // vertex shown as v0,v1,v2
  37364. // interp index is i1 to progress in range [v0,v1[
  37365. // interp index is i2 to progress in range [v0,v2[
  37366. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37367. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37368. //
  37369. //
  37370. // i2 v2
  37371. // ^ ^
  37372. // / / \
  37373. // / / \
  37374. // / / \
  37375. // / / (0,1) \
  37376. // / #---------\
  37377. // / / \ (0,0)'/ \
  37378. // / / \ / \
  37379. // / / \ / \
  37380. // / / (0,0) \ / (1,0) \
  37381. // / #---------#---------\
  37382. // v0 v1
  37383. //
  37384. // --------------------> i1
  37385. //
  37386. // interp of (i1,i2):
  37387. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37388. // along i1 : lerp(x0,x1, i1/(S-i2))
  37389. //
  37390. // centroid of triangle is needed to get help normal computation
  37391. // (c1,c2) are used for centroid location
  37392. var interp_vertex = function (i1, i2, c1, c2) {
  37393. // vertex is interpolated from
  37394. // - face_vertex_pos[0..2]
  37395. // - face_vertex_uv[0..2]
  37396. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37397. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37398. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37399. pos_interp.normalize();
  37400. var vertex_normal;
  37401. if (flat) {
  37402. // in flat mode, recalculate normal as face centroid normal
  37403. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37404. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37405. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37406. }
  37407. else {
  37408. // in smooth mode, recalculate normal from each single vertex position
  37409. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37410. }
  37411. // Vertex normal need correction due to X,Y,Z radius scaling
  37412. vertex_normal.x /= radiusX;
  37413. vertex_normal.y /= radiusY;
  37414. vertex_normal.z /= radiusZ;
  37415. vertex_normal.normalize();
  37416. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37417. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37418. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37419. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37420. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37421. uvs.push(uv_interp.x, uv_interp.y);
  37422. // push each vertex has member of a face
  37423. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37424. indices.push(current_indice);
  37425. current_indice++;
  37426. };
  37427. for (var i2 = 0; i2 < subdivisions; i2++) {
  37428. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37429. // face : (i1,i2) for /\ :
  37430. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37431. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37432. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37433. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37434. if (i1 + i2 + 1 < subdivisions) {
  37435. // face : (i1,i2)' for \/ :
  37436. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37437. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37438. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37439. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37440. }
  37441. }
  37442. }
  37443. }
  37444. // Sides
  37445. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37446. // Result
  37447. var vertexData = new VertexData();
  37448. vertexData.indices = indices;
  37449. vertexData.positions = positions;
  37450. vertexData.normals = normals;
  37451. vertexData.uvs = uvs;
  37452. return vertexData;
  37453. };
  37454. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37455. /**
  37456. * Creates the VertexData for a Polyhedron
  37457. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37458. * * type provided types are:
  37459. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37460. * * 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)
  37461. * * size the size of the IcoSphere, optional default 1
  37462. * * sizeX allows stretching in the x direction, optional, default size
  37463. * * sizeY allows stretching in the y direction, optional, default size
  37464. * * sizeZ allows stretching in the z direction, optional, default size
  37465. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37466. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37467. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37468. * * flat when true creates a flat shaded mesh, optional, default true
  37469. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37470. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37471. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37472. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37473. * @returns the VertexData of the Polyhedron
  37474. */
  37475. VertexData.CreatePolyhedron = function (options) {
  37476. // provided polyhedron types :
  37477. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37478. // 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)
  37479. var polyhedra = [];
  37480. 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]] };
  37481. 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]] };
  37482. polyhedra[2] = {
  37483. 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]],
  37484. 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]]
  37485. };
  37486. polyhedra[3] = {
  37487. 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]],
  37488. 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]]
  37489. };
  37490. polyhedra[4] = {
  37491. 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]],
  37492. 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]]
  37493. };
  37494. 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]] };
  37495. 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]] };
  37496. 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]] };
  37497. 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]] };
  37498. 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]] };
  37499. 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]] };
  37500. 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]] };
  37501. 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]] };
  37502. 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]] };
  37503. polyhedra[14] = {
  37504. 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]],
  37505. 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]]
  37506. };
  37507. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37508. var size = options.size;
  37509. var sizeX = options.sizeX || size || 1;
  37510. var sizeY = options.sizeY || size || 1;
  37511. var sizeZ = options.sizeZ || size || 1;
  37512. var data = options.custom || polyhedra[type];
  37513. var nbfaces = data.face.length;
  37514. var faceUV = options.faceUV || new Array(nbfaces);
  37515. var faceColors = options.faceColors;
  37516. var flat = (options.flat === undefined) ? true : options.flat;
  37517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37518. var positions = new Array();
  37519. var indices = new Array();
  37520. var normals = new Array();
  37521. var uvs = new Array();
  37522. var colors = new Array();
  37523. var index = 0;
  37524. var faceIdx = 0; // face cursor in the array "indexes"
  37525. var indexes = new Array();
  37526. var i = 0;
  37527. var f = 0;
  37528. var u, v, ang, x, y, tmp;
  37529. // default face colors and UV if undefined
  37530. if (flat) {
  37531. for (f = 0; f < nbfaces; f++) {
  37532. if (faceColors && faceColors[f] === undefined) {
  37533. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37534. }
  37535. if (faceUV && faceUV[f] === undefined) {
  37536. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37537. }
  37538. }
  37539. }
  37540. if (!flat) {
  37541. for (i = 0; i < data.vertex.length; i++) {
  37542. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37543. uvs.push(0, 0);
  37544. }
  37545. for (f = 0; f < nbfaces; f++) {
  37546. for (i = 0; i < data.face[f].length - 2; i++) {
  37547. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37548. }
  37549. }
  37550. }
  37551. else {
  37552. for (f = 0; f < nbfaces; f++) {
  37553. var fl = data.face[f].length; // number of vertices of the current face
  37554. ang = 2 * Math.PI / fl;
  37555. x = 0.5 * Math.tan(ang / 2);
  37556. y = 0.5;
  37557. // positions, uvs, colors
  37558. for (i = 0; i < fl; i++) {
  37559. // positions
  37560. 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);
  37561. indexes.push(index);
  37562. index++;
  37563. // uvs
  37564. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37565. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37566. uvs.push(u, v);
  37567. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37568. y = x * Math.sin(ang) + y * Math.cos(ang);
  37569. x = tmp;
  37570. // colors
  37571. if (faceColors) {
  37572. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37573. }
  37574. }
  37575. // indices from indexes
  37576. for (i = 0; i < fl - 2; i++) {
  37577. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37578. }
  37579. faceIdx += fl;
  37580. }
  37581. }
  37582. VertexData.ComputeNormals(positions, indices, normals);
  37583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37584. var vertexData = new VertexData();
  37585. vertexData.positions = positions;
  37586. vertexData.indices = indices;
  37587. vertexData.normals = normals;
  37588. vertexData.uvs = uvs;
  37589. if (faceColors && flat) {
  37590. vertexData.colors = colors;
  37591. }
  37592. return vertexData;
  37593. };
  37594. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37595. /**
  37596. * Creates the VertexData for a TorusKnot
  37597. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37598. * * radius the radius of the torus knot, optional, default 2
  37599. * * tube the thickness of the tube, optional, default 0.5
  37600. * * radialSegments the number of sides on each tube segments, optional, default 32
  37601. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37602. * * p the number of windings around the z axis, optional, default 2
  37603. * * q the number of windings around the x axis, optional, default 3
  37604. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37605. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37606. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37607. * @returns the VertexData of the Torus Knot
  37608. */
  37609. VertexData.CreateTorusKnot = function (options) {
  37610. var indices = new Array();
  37611. var positions = new Array();
  37612. var normals = new Array();
  37613. var uvs = new Array();
  37614. var radius = options.radius || 2;
  37615. var tube = options.tube || 0.5;
  37616. var radialSegments = options.radialSegments || 32;
  37617. var tubularSegments = options.tubularSegments || 32;
  37618. var p = options.p || 2;
  37619. var q = options.q || 3;
  37620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37621. // Helper
  37622. var getPos = function (angle) {
  37623. var cu = Math.cos(angle);
  37624. var su = Math.sin(angle);
  37625. var quOverP = q / p * angle;
  37626. var cs = Math.cos(quOverP);
  37627. var tx = radius * (2 + cs) * 0.5 * cu;
  37628. var ty = radius * (2 + cs) * su * 0.5;
  37629. var tz = radius * Math.sin(quOverP) * 0.5;
  37630. return new BABYLON.Vector3(tx, ty, tz);
  37631. };
  37632. // Vertices
  37633. var i;
  37634. var j;
  37635. for (i = 0; i <= radialSegments; i++) {
  37636. var modI = i % radialSegments;
  37637. var u = modI / radialSegments * 2 * p * Math.PI;
  37638. var p1 = getPos(u);
  37639. var p2 = getPos(u + 0.01);
  37640. var tang = p2.subtract(p1);
  37641. var n = p2.add(p1);
  37642. var bitan = BABYLON.Vector3.Cross(tang, n);
  37643. n = BABYLON.Vector3.Cross(bitan, tang);
  37644. bitan.normalize();
  37645. n.normalize();
  37646. for (j = 0; j < tubularSegments; j++) {
  37647. var modJ = j % tubularSegments;
  37648. var v = modJ / tubularSegments * 2 * Math.PI;
  37649. var cx = -tube * Math.cos(v);
  37650. var cy = tube * Math.sin(v);
  37651. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37652. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37653. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37654. uvs.push(i / radialSegments);
  37655. uvs.push(j / tubularSegments);
  37656. }
  37657. }
  37658. for (i = 0; i < radialSegments; i++) {
  37659. for (j = 0; j < tubularSegments; j++) {
  37660. var jNext = (j + 1) % tubularSegments;
  37661. var a = i * tubularSegments + j;
  37662. var b = (i + 1) * tubularSegments + j;
  37663. var c = (i + 1) * tubularSegments + jNext;
  37664. var d = i * tubularSegments + jNext;
  37665. indices.push(d);
  37666. indices.push(b);
  37667. indices.push(a);
  37668. indices.push(d);
  37669. indices.push(c);
  37670. indices.push(b);
  37671. }
  37672. }
  37673. // Normals
  37674. VertexData.ComputeNormals(positions, indices, normals);
  37675. // Sides
  37676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37677. // Result
  37678. var vertexData = new VertexData();
  37679. vertexData.indices = indices;
  37680. vertexData.positions = positions;
  37681. vertexData.normals = normals;
  37682. vertexData.uvs = uvs;
  37683. return vertexData;
  37684. };
  37685. // Tools
  37686. /**
  37687. * Compute normals for given positions and indices
  37688. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37689. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37690. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37691. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37692. * * facetNormals : optional array of facet normals (vector3)
  37693. * * facetPositions : optional array of facet positions (vector3)
  37694. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37695. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37696. * * bInfo : optional bounding info, required for facetPartitioning computation
  37697. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37698. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37699. * * useRightHandedSystem: optional boolean to for right handed system computation
  37700. * * depthSort : optional boolean to enable the facet depth sort computation
  37701. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37702. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37703. */
  37704. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37705. // temporary scalar variables
  37706. var index = 0; // facet index
  37707. var p1p2x = 0.0; // p1p2 vector x coordinate
  37708. var p1p2y = 0.0; // p1p2 vector y coordinate
  37709. var p1p2z = 0.0; // p1p2 vector z coordinate
  37710. var p3p2x = 0.0; // p3p2 vector x coordinate
  37711. var p3p2y = 0.0; // p3p2 vector y coordinate
  37712. var p3p2z = 0.0; // p3p2 vector z coordinate
  37713. var faceNormalx = 0.0; // facet normal x coordinate
  37714. var faceNormaly = 0.0; // facet normal y coordinate
  37715. var faceNormalz = 0.0; // facet normal z coordinate
  37716. var length = 0.0; // facet normal length before normalization
  37717. var v1x = 0; // vector1 x index in the positions array
  37718. var v1y = 0; // vector1 y index in the positions array
  37719. var v1z = 0; // vector1 z index in the positions array
  37720. var v2x = 0; // vector2 x index in the positions array
  37721. var v2y = 0; // vector2 y index in the positions array
  37722. var v2z = 0; // vector2 z index in the positions array
  37723. var v3x = 0; // vector3 x index in the positions array
  37724. var v3y = 0; // vector3 y index in the positions array
  37725. var v3z = 0; // vector3 z index in the positions array
  37726. var computeFacetNormals = false;
  37727. var computeFacetPositions = false;
  37728. var computeFacetPartitioning = false;
  37729. var computeDepthSort = false;
  37730. var faceNormalSign = 1;
  37731. var ratio = 0;
  37732. var distanceTo = null;
  37733. if (options) {
  37734. computeFacetNormals = (options.facetNormals) ? true : false;
  37735. computeFacetPositions = (options.facetPositions) ? true : false;
  37736. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37737. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37738. ratio = options.ratio || 0;
  37739. computeDepthSort = (options.depthSort) ? true : false;
  37740. distanceTo = (options.distanceTo);
  37741. if (computeDepthSort) {
  37742. if (distanceTo === undefined) {
  37743. distanceTo = BABYLON.Vector3.Zero();
  37744. }
  37745. var depthSortedFacets = options.depthSortedFacets;
  37746. }
  37747. }
  37748. // facetPartitioning reinit if needed
  37749. var xSubRatio = 0;
  37750. var ySubRatio = 0;
  37751. var zSubRatio = 0;
  37752. var subSq = 0;
  37753. if (computeFacetPartitioning && options && options.bbSize) {
  37754. var ox = 0; // X partitioning index for facet position
  37755. var oy = 0; // Y partinioning index for facet position
  37756. var oz = 0; // Z partinioning index for facet position
  37757. var b1x = 0; // X partitioning index for facet v1 vertex
  37758. var b1y = 0; // Y partitioning index for facet v1 vertex
  37759. var b1z = 0; // z partitioning index for facet v1 vertex
  37760. var b2x = 0; // X partitioning index for facet v2 vertex
  37761. var b2y = 0; // Y partitioning index for facet v2 vertex
  37762. var b2z = 0; // Z partitioning index for facet v2 vertex
  37763. var b3x = 0; // X partitioning index for facet v3 vertex
  37764. var b3y = 0; // Y partitioning index for facet v3 vertex
  37765. var b3z = 0; // Z partitioning index for facet v3 vertex
  37766. var block_idx_o = 0; // facet barycenter block index
  37767. var block_idx_v1 = 0; // v1 vertex block index
  37768. var block_idx_v2 = 0; // v2 vertex block index
  37769. var block_idx_v3 = 0; // v3 vertex block index
  37770. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37771. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37772. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37773. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37774. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37775. subSq = options.subDiv.max * options.subDiv.max;
  37776. options.facetPartitioning.length = 0;
  37777. }
  37778. // reset the normals
  37779. for (index = 0; index < positions.length; index++) {
  37780. normals[index] = 0.0;
  37781. }
  37782. // Loop : 1 indice triplet = 1 facet
  37783. var nbFaces = (indices.length / 3) | 0;
  37784. for (index = 0; index < nbFaces; index++) {
  37785. // get the indexes of the coordinates of each vertex of the facet
  37786. v1x = indices[index * 3] * 3;
  37787. v1y = v1x + 1;
  37788. v1z = v1x + 2;
  37789. v2x = indices[index * 3 + 1] * 3;
  37790. v2y = v2x + 1;
  37791. v2z = v2x + 2;
  37792. v3x = indices[index * 3 + 2] * 3;
  37793. v3y = v3x + 1;
  37794. v3z = v3x + 2;
  37795. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37796. p1p2y = positions[v1y] - positions[v2y];
  37797. p1p2z = positions[v1z] - positions[v2z];
  37798. p3p2x = positions[v3x] - positions[v2x];
  37799. p3p2y = positions[v3y] - positions[v2y];
  37800. p3p2z = positions[v3z] - positions[v2z];
  37801. // compute the face normal with the cross product
  37802. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37803. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37804. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37805. // normalize this normal and store it in the array facetData
  37806. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37807. length = (length === 0) ? 1.0 : length;
  37808. faceNormalx /= length;
  37809. faceNormaly /= length;
  37810. faceNormalz /= length;
  37811. if (computeFacetNormals && options) {
  37812. options.facetNormals[index].x = faceNormalx;
  37813. options.facetNormals[index].y = faceNormaly;
  37814. options.facetNormals[index].z = faceNormalz;
  37815. }
  37816. if (computeFacetPositions && options) {
  37817. // compute and the facet barycenter coordinates in the array facetPositions
  37818. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37819. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37820. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37821. }
  37822. if (computeFacetPartitioning && options) {
  37823. // store the facet indexes in arrays in the main facetPartitioning array :
  37824. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37825. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37826. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37827. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37828. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37829. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37830. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37831. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37832. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37833. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37834. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37835. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37836. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37837. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37838. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37839. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37840. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37841. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37842. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37843. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37844. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37845. // push each facet index in each block containing the vertex
  37846. options.facetPartitioning[block_idx_v1].push(index);
  37847. if (block_idx_v2 != block_idx_v1) {
  37848. options.facetPartitioning[block_idx_v2].push(index);
  37849. }
  37850. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37851. options.facetPartitioning[block_idx_v3].push(index);
  37852. }
  37853. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37854. options.facetPartitioning[block_idx_o].push(index);
  37855. }
  37856. }
  37857. if (computeDepthSort && options && options.facetPositions) {
  37858. var dsf = depthSortedFacets[index];
  37859. dsf.ind = index * 3;
  37860. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37861. }
  37862. // compute the normals anyway
  37863. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37864. normals[v1y] += faceNormaly;
  37865. normals[v1z] += faceNormalz;
  37866. normals[v2x] += faceNormalx;
  37867. normals[v2y] += faceNormaly;
  37868. normals[v2z] += faceNormalz;
  37869. normals[v3x] += faceNormalx;
  37870. normals[v3y] += faceNormaly;
  37871. normals[v3z] += faceNormalz;
  37872. }
  37873. // last normalization of each normal
  37874. for (index = 0; index < normals.length / 3; index++) {
  37875. faceNormalx = normals[index * 3];
  37876. faceNormaly = normals[index * 3 + 1];
  37877. faceNormalz = normals[index * 3 + 2];
  37878. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37879. length = (length === 0) ? 1.0 : length;
  37880. faceNormalx /= length;
  37881. faceNormaly /= length;
  37882. faceNormalz /= length;
  37883. normals[index * 3] = faceNormalx;
  37884. normals[index * 3 + 1] = faceNormaly;
  37885. normals[index * 3 + 2] = faceNormalz;
  37886. }
  37887. };
  37888. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37889. var li = indices.length;
  37890. var ln = normals.length;
  37891. var i;
  37892. var n;
  37893. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37894. switch (sideOrientation) {
  37895. case BABYLON.Mesh.FRONTSIDE:
  37896. // nothing changed
  37897. break;
  37898. case BABYLON.Mesh.BACKSIDE:
  37899. var tmp;
  37900. // indices
  37901. for (i = 0; i < li; i += 3) {
  37902. tmp = indices[i];
  37903. indices[i] = indices[i + 2];
  37904. indices[i + 2] = tmp;
  37905. }
  37906. // normals
  37907. for (n = 0; n < ln; n++) {
  37908. normals[n] = -normals[n];
  37909. }
  37910. break;
  37911. case BABYLON.Mesh.DOUBLESIDE:
  37912. // positions
  37913. var lp = positions.length;
  37914. var l = lp / 3;
  37915. for (var p = 0; p < lp; p++) {
  37916. positions[lp + p] = positions[p];
  37917. }
  37918. // indices
  37919. for (i = 0; i < li; i += 3) {
  37920. indices[i + li] = indices[i + 2] + l;
  37921. indices[i + 1 + li] = indices[i + 1] + l;
  37922. indices[i + 2 + li] = indices[i] + l;
  37923. }
  37924. // normals
  37925. for (n = 0; n < ln; n++) {
  37926. normals[ln + n] = -normals[n];
  37927. }
  37928. // uvs
  37929. var lu = uvs.length;
  37930. var u = 0;
  37931. for (u = 0; u < lu; u++) {
  37932. uvs[u + lu] = uvs[u];
  37933. }
  37934. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37935. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37936. u = 0;
  37937. for (i = 0; i < lu / 2; i++) {
  37938. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37939. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37940. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37941. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37942. u += 2;
  37943. }
  37944. break;
  37945. }
  37946. };
  37947. /**
  37948. * Applies VertexData created from the imported parameters to the geometry
  37949. * @param parsedVertexData the parsed data from an imported file
  37950. * @param geometry the geometry to apply the VertexData to
  37951. */
  37952. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37953. var vertexData = new VertexData();
  37954. // positions
  37955. var positions = parsedVertexData.positions;
  37956. if (positions) {
  37957. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37958. }
  37959. // normals
  37960. var normals = parsedVertexData.normals;
  37961. if (normals) {
  37962. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37963. }
  37964. // tangents
  37965. var tangents = parsedVertexData.tangents;
  37966. if (tangents) {
  37967. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37968. }
  37969. // uvs
  37970. var uvs = parsedVertexData.uvs;
  37971. if (uvs) {
  37972. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37973. }
  37974. // uv2s
  37975. var uv2s = parsedVertexData.uv2s;
  37976. if (uv2s) {
  37977. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37978. }
  37979. // uv3s
  37980. var uv3s = parsedVertexData.uv3s;
  37981. if (uv3s) {
  37982. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37983. }
  37984. // uv4s
  37985. var uv4s = parsedVertexData.uv4s;
  37986. if (uv4s) {
  37987. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37988. }
  37989. // uv5s
  37990. var uv5s = parsedVertexData.uv5s;
  37991. if (uv5s) {
  37992. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37993. }
  37994. // uv6s
  37995. var uv6s = parsedVertexData.uv6s;
  37996. if (uv6s) {
  37997. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37998. }
  37999. // colors
  38000. var colors = parsedVertexData.colors;
  38001. if (colors) {
  38002. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38003. }
  38004. // matricesIndices
  38005. var matricesIndices = parsedVertexData.matricesIndices;
  38006. if (matricesIndices) {
  38007. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38008. }
  38009. // matricesWeights
  38010. var matricesWeights = parsedVertexData.matricesWeights;
  38011. if (matricesWeights) {
  38012. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38013. }
  38014. // indices
  38015. var indices = parsedVertexData.indices;
  38016. if (indices) {
  38017. vertexData.indices = indices;
  38018. }
  38019. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38020. };
  38021. return VertexData;
  38022. }());
  38023. BABYLON.VertexData = VertexData;
  38024. })(BABYLON || (BABYLON = {}));
  38025. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38026. var BABYLON;
  38027. (function (BABYLON) {
  38028. /**
  38029. * Class used to store geometry data (vertex buffers + index buffer)
  38030. */
  38031. var Geometry = /** @class */ (function () {
  38032. /**
  38033. * Creates a new geometry
  38034. * @param id defines the unique ID
  38035. * @param scene defines the hosting scene
  38036. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38037. * @param updatable defines if geometry must be updatable (false by default)
  38038. * @param mesh defines the mesh that will be associated with the geometry
  38039. */
  38040. function Geometry(id, scene, vertexData, updatable, mesh) {
  38041. if (updatable === void 0) { updatable = false; }
  38042. if (mesh === void 0) { mesh = null; }
  38043. /**
  38044. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38045. */
  38046. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38047. this._totalVertices = 0;
  38048. this._isDisposed = false;
  38049. this._indexBufferIsUpdatable = false;
  38050. this.id = id;
  38051. this._engine = scene.getEngine();
  38052. this._meshes = [];
  38053. this._scene = scene;
  38054. //Init vertex buffer cache
  38055. this._vertexBuffers = {};
  38056. this._indices = [];
  38057. this._updatable = updatable;
  38058. // vertexData
  38059. if (vertexData) {
  38060. this.setAllVerticesData(vertexData, updatable);
  38061. }
  38062. else {
  38063. this._totalVertices = 0;
  38064. this._indices = [];
  38065. }
  38066. if (this._engine.getCaps().vertexArrayObject) {
  38067. this._vertexArrayObjects = {};
  38068. }
  38069. // applyToMesh
  38070. if (mesh) {
  38071. if (mesh.getClassName() === "LinesMesh") {
  38072. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38073. this._updateExtend();
  38074. }
  38075. this.applyToMesh(mesh);
  38076. mesh.computeWorldMatrix(true);
  38077. }
  38078. }
  38079. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38080. /**
  38081. * 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
  38082. */
  38083. get: function () {
  38084. return this._boundingBias;
  38085. },
  38086. /**
  38087. * 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
  38088. */
  38089. set: function (value) {
  38090. if (this._boundingBias && this._boundingBias.equals(value)) {
  38091. return;
  38092. }
  38093. this._boundingBias = value.clone();
  38094. this._updateBoundingInfo(true, null);
  38095. },
  38096. enumerable: true,
  38097. configurable: true
  38098. });
  38099. /**
  38100. * Static function used to attach a new empty geometry to a mesh
  38101. * @param mesh defines the mesh to attach the geometry to
  38102. * @returns the new {BABYLON.Geometry}
  38103. */
  38104. Geometry.CreateGeometryForMesh = function (mesh) {
  38105. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38106. geometry.applyToMesh(mesh);
  38107. return geometry;
  38108. };
  38109. Object.defineProperty(Geometry.prototype, "extend", {
  38110. /**
  38111. * Gets the current extend of the geometry
  38112. */
  38113. get: function () {
  38114. return this._extend;
  38115. },
  38116. enumerable: true,
  38117. configurable: true
  38118. });
  38119. /**
  38120. * Gets the hosting scene
  38121. * @returns the hosting {BABYLON.Scene}
  38122. */
  38123. Geometry.prototype.getScene = function () {
  38124. return this._scene;
  38125. };
  38126. /**
  38127. * Gets the hosting engine
  38128. * @returns the hosting {BABYLON.Engine}
  38129. */
  38130. Geometry.prototype.getEngine = function () {
  38131. return this._engine;
  38132. };
  38133. /**
  38134. * Defines if the geometry is ready to use
  38135. * @returns true if the geometry is ready to be used
  38136. */
  38137. Geometry.prototype.isReady = function () {
  38138. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38139. };
  38140. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38141. /**
  38142. * Gets a value indicating that the geometry should not be serialized
  38143. */
  38144. get: function () {
  38145. for (var index = 0; index < this._meshes.length; index++) {
  38146. if (!this._meshes[index].doNotSerialize) {
  38147. return false;
  38148. }
  38149. }
  38150. return true;
  38151. },
  38152. enumerable: true,
  38153. configurable: true
  38154. });
  38155. /** @ignore */
  38156. Geometry.prototype._rebuild = function () {
  38157. if (this._vertexArrayObjects) {
  38158. this._vertexArrayObjects = {};
  38159. }
  38160. // Index buffer
  38161. if (this._meshes.length !== 0 && this._indices) {
  38162. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38163. }
  38164. // Vertex buffers
  38165. for (var key in this._vertexBuffers) {
  38166. var vertexBuffer = this._vertexBuffers[key];
  38167. vertexBuffer._rebuild();
  38168. }
  38169. };
  38170. /**
  38171. * Affects all gemetry data in one call
  38172. * @param vertexData defines the geometry data
  38173. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38174. */
  38175. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38176. vertexData.applyToGeometry(this, updatable);
  38177. this.notifyUpdate();
  38178. };
  38179. /**
  38180. * Set specific vertex data
  38181. * @param kind defines the data kind (Position, normal, etc...)
  38182. * @param data defines the vertex data to use
  38183. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38184. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38185. */
  38186. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38187. if (updatable === void 0) { updatable = false; }
  38188. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38189. this.setVerticesBuffer(buffer);
  38190. };
  38191. /**
  38192. * Removes a specific vertex data
  38193. * @param kind defines the data kind (Position, normal, etc...)
  38194. */
  38195. Geometry.prototype.removeVerticesData = function (kind) {
  38196. if (this._vertexBuffers[kind]) {
  38197. this._vertexBuffers[kind].dispose();
  38198. delete this._vertexBuffers[kind];
  38199. }
  38200. };
  38201. /**
  38202. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38203. * @param buffer defines the vertex buffer to use
  38204. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38205. */
  38206. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38207. if (totalVertices === void 0) { totalVertices = null; }
  38208. var kind = buffer.getKind();
  38209. if (this._vertexBuffers[kind]) {
  38210. this._vertexBuffers[kind].dispose();
  38211. }
  38212. this._vertexBuffers[kind] = buffer;
  38213. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38214. var data = buffer.getData();
  38215. if (totalVertices != null) {
  38216. this._totalVertices = totalVertices;
  38217. }
  38218. else {
  38219. if (data != null) {
  38220. this._totalVertices = data.length / (buffer.byteStride / 4);
  38221. }
  38222. }
  38223. this._updateExtend(data);
  38224. this._resetPointsArrayCache();
  38225. var meshes = this._meshes;
  38226. var numOfMeshes = meshes.length;
  38227. for (var index = 0; index < numOfMeshes; index++) {
  38228. var mesh = meshes[index];
  38229. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38230. mesh._createGlobalSubMesh(false);
  38231. mesh.computeWorldMatrix(true);
  38232. }
  38233. }
  38234. this.notifyUpdate(kind);
  38235. if (this._vertexArrayObjects) {
  38236. this._disposeVertexArrayObjects();
  38237. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38238. }
  38239. };
  38240. /**
  38241. * Update a specific vertex buffer
  38242. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38243. * It will do nothing if the buffer is not updatable
  38244. * @param kind defines the data kind (Position, normal, etc...)
  38245. * @param data defines the data to use
  38246. * @param offset defines the offset in the target buffer where to store the data
  38247. * @param useBytes set to true if the offset is in bytes
  38248. */
  38249. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38250. if (useBytes === void 0) { useBytes = false; }
  38251. var vertexBuffer = this.getVertexBuffer(kind);
  38252. if (!vertexBuffer) {
  38253. return;
  38254. }
  38255. vertexBuffer.updateDirectly(data, offset, useBytes);
  38256. this.notifyUpdate(kind);
  38257. };
  38258. /**
  38259. * Update a specific vertex buffer
  38260. * This function will create a new buffer if the current one is not updatable
  38261. * @param kind defines the data kind (Position, normal, etc...)
  38262. * @param data defines the data to use
  38263. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38264. */
  38265. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38266. if (updateExtends === void 0) { updateExtends = false; }
  38267. var vertexBuffer = this.getVertexBuffer(kind);
  38268. if (!vertexBuffer) {
  38269. return;
  38270. }
  38271. vertexBuffer.update(data);
  38272. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38273. this._updateBoundingInfo(updateExtends, data);
  38274. }
  38275. this.notifyUpdate(kind);
  38276. };
  38277. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38278. if (updateExtends) {
  38279. this._updateExtend(data);
  38280. }
  38281. var meshes = this._meshes;
  38282. var numOfMeshes = meshes.length;
  38283. this._resetPointsArrayCache();
  38284. for (var index = 0; index < numOfMeshes; index++) {
  38285. var mesh = meshes[index];
  38286. if (updateExtends) {
  38287. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38288. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38289. var subMesh = mesh.subMeshes[subIndex];
  38290. subMesh.refreshBoundingInfo();
  38291. }
  38292. }
  38293. }
  38294. };
  38295. /** @ignore */
  38296. Geometry.prototype._bind = function (effect, indexToBind) {
  38297. if (!effect) {
  38298. return;
  38299. }
  38300. if (indexToBind === undefined) {
  38301. indexToBind = this._indexBuffer;
  38302. }
  38303. var vbs = this.getVertexBuffers();
  38304. if (!vbs) {
  38305. return;
  38306. }
  38307. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38308. this._engine.bindBuffers(vbs, indexToBind, effect);
  38309. return;
  38310. }
  38311. // Using VAO
  38312. if (!this._vertexArrayObjects[effect.key]) {
  38313. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38314. }
  38315. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38316. };
  38317. /**
  38318. * Gets total number of vertices
  38319. * @returns the total number of vertices
  38320. */
  38321. Geometry.prototype.getTotalVertices = function () {
  38322. if (!this.isReady()) {
  38323. return 0;
  38324. }
  38325. return this._totalVertices;
  38326. };
  38327. /**
  38328. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38329. * @param kind defines the data kind (Position, normal, etc...)
  38330. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38331. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38332. * @returns a float array containing vertex data
  38333. */
  38334. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38335. var vertexBuffer = this.getVertexBuffer(kind);
  38336. if (!vertexBuffer) {
  38337. return null;
  38338. }
  38339. var data = vertexBuffer.getData();
  38340. if (!data) {
  38341. return null;
  38342. }
  38343. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38344. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38345. var count = this._totalVertices * defaultStride;
  38346. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38347. var copy_1 = new Array(count);
  38348. vertexBuffer.forEach(count, function (value, index) {
  38349. copy_1[index] = value;
  38350. });
  38351. return copy_1;
  38352. }
  38353. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38354. if (data instanceof Array) {
  38355. var offset = vertexBuffer.byteOffset / 4;
  38356. return BABYLON.Tools.Slice(data, offset, offset + count);
  38357. }
  38358. else if (data instanceof ArrayBuffer) {
  38359. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38360. }
  38361. else {
  38362. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38363. }
  38364. }
  38365. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38366. return BABYLON.Tools.Slice(data);
  38367. }
  38368. return data;
  38369. };
  38370. /**
  38371. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38372. * @param kind defines the data kind (Position, normal, etc...)
  38373. * @returns true if the vertex buffer with the specified kind is updatable
  38374. */
  38375. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38376. var vb = this._vertexBuffers[kind];
  38377. if (!vb) {
  38378. return false;
  38379. }
  38380. return vb.isUpdatable();
  38381. };
  38382. /**
  38383. * Gets a specific vertex buffer
  38384. * @param kind defines the data kind (Position, normal, etc...)
  38385. * @returns a {BABYLON.VertexBuffer}
  38386. */
  38387. Geometry.prototype.getVertexBuffer = function (kind) {
  38388. if (!this.isReady()) {
  38389. return null;
  38390. }
  38391. return this._vertexBuffers[kind];
  38392. };
  38393. /**
  38394. * Returns all vertex buffers
  38395. * @return an object holding all vertex buffers indexed by kind
  38396. */
  38397. Geometry.prototype.getVertexBuffers = function () {
  38398. if (!this.isReady()) {
  38399. return null;
  38400. }
  38401. return this._vertexBuffers;
  38402. };
  38403. /**
  38404. * Gets a boolean indicating if specific vertex buffer is present
  38405. * @param kind defines the data kind (Position, normal, etc...)
  38406. * @returns true if data is present
  38407. */
  38408. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38409. if (!this._vertexBuffers) {
  38410. if (this._delayInfo) {
  38411. return this._delayInfo.indexOf(kind) !== -1;
  38412. }
  38413. return false;
  38414. }
  38415. return this._vertexBuffers[kind] !== undefined;
  38416. };
  38417. /**
  38418. * Gets a list of all attached data kinds (Position, normal, etc...)
  38419. * @returns a list of string containing all kinds
  38420. */
  38421. Geometry.prototype.getVerticesDataKinds = function () {
  38422. var result = [];
  38423. var kind;
  38424. if (!this._vertexBuffers && this._delayInfo) {
  38425. for (kind in this._delayInfo) {
  38426. result.push(kind);
  38427. }
  38428. }
  38429. else {
  38430. for (kind in this._vertexBuffers) {
  38431. result.push(kind);
  38432. }
  38433. }
  38434. return result;
  38435. };
  38436. /**
  38437. * Update index buffer
  38438. * @param indices defines the indices to store in the index buffer
  38439. * @param offset defines the offset in the target buffer where to store the data
  38440. */
  38441. Geometry.prototype.updateIndices = function (indices, offset) {
  38442. if (!this._indexBuffer) {
  38443. return;
  38444. }
  38445. if (!this._indexBufferIsUpdatable) {
  38446. this.setIndices(indices, null, true);
  38447. }
  38448. else {
  38449. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38450. }
  38451. };
  38452. /**
  38453. * Creates a new index buffer
  38454. * @param indices defines the indices to store in the index buffer
  38455. * @param totalVertices defines the total number of vertices (could be null)
  38456. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38457. */
  38458. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38459. if (totalVertices === void 0) { totalVertices = null; }
  38460. if (updatable === void 0) { updatable = false; }
  38461. if (this._indexBuffer) {
  38462. this._engine._releaseBuffer(this._indexBuffer);
  38463. }
  38464. this._disposeVertexArrayObjects();
  38465. this._indices = indices;
  38466. this._indexBufferIsUpdatable = updatable;
  38467. if (this._meshes.length !== 0 && this._indices) {
  38468. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38469. }
  38470. if (totalVertices != undefined) { // including null and undefined
  38471. this._totalVertices = totalVertices;
  38472. }
  38473. var meshes = this._meshes;
  38474. var numOfMeshes = meshes.length;
  38475. for (var index = 0; index < numOfMeshes; index++) {
  38476. meshes[index]._createGlobalSubMesh(true);
  38477. }
  38478. this.notifyUpdate();
  38479. };
  38480. /**
  38481. * Return the total number of indices
  38482. * @returns the total number of indices
  38483. */
  38484. Geometry.prototype.getTotalIndices = function () {
  38485. if (!this.isReady()) {
  38486. return 0;
  38487. }
  38488. return this._indices.length;
  38489. };
  38490. /**
  38491. * Gets the index buffer array
  38492. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38493. * @returns the index buffer array
  38494. */
  38495. Geometry.prototype.getIndices = function (copyWhenShared) {
  38496. if (!this.isReady()) {
  38497. return null;
  38498. }
  38499. var orig = this._indices;
  38500. if (!copyWhenShared || this._meshes.length === 1) {
  38501. return orig;
  38502. }
  38503. else {
  38504. var len = orig.length;
  38505. var copy = [];
  38506. for (var i = 0; i < len; i++) {
  38507. copy.push(orig[i]);
  38508. }
  38509. return copy;
  38510. }
  38511. };
  38512. /**
  38513. * Gets the index buffer
  38514. * @return the index buffer
  38515. */
  38516. Geometry.prototype.getIndexBuffer = function () {
  38517. if (!this.isReady()) {
  38518. return null;
  38519. }
  38520. return this._indexBuffer;
  38521. };
  38522. /** @ignore */
  38523. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38524. if (effect === void 0) { effect = null; }
  38525. if (!effect || !this._vertexArrayObjects) {
  38526. return;
  38527. }
  38528. if (this._vertexArrayObjects[effect.key]) {
  38529. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38530. delete this._vertexArrayObjects[effect.key];
  38531. }
  38532. };
  38533. /**
  38534. * Release the associated resources for a specific mesh
  38535. * @param mesh defines the source mesh
  38536. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38537. */
  38538. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38539. var meshes = this._meshes;
  38540. var index = meshes.indexOf(mesh);
  38541. if (index === -1) {
  38542. return;
  38543. }
  38544. meshes.splice(index, 1);
  38545. mesh._geometry = null;
  38546. if (meshes.length === 0 && shouldDispose) {
  38547. this.dispose();
  38548. }
  38549. };
  38550. /**
  38551. * Apply current geometry to a given mesh
  38552. * @param mesh defines the mesh to apply geometry to
  38553. */
  38554. Geometry.prototype.applyToMesh = function (mesh) {
  38555. if (mesh._geometry === this) {
  38556. return;
  38557. }
  38558. var previousGeometry = mesh._geometry;
  38559. if (previousGeometry) {
  38560. previousGeometry.releaseForMesh(mesh);
  38561. }
  38562. var meshes = this._meshes;
  38563. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38564. mesh._geometry = this;
  38565. this._scene.pushGeometry(this);
  38566. meshes.push(mesh);
  38567. if (this.isReady()) {
  38568. this._applyToMesh(mesh);
  38569. }
  38570. else {
  38571. mesh._boundingInfo = this._boundingInfo;
  38572. }
  38573. };
  38574. Geometry.prototype._updateExtend = function (data) {
  38575. if (data === void 0) { data = null; }
  38576. if (!data) {
  38577. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38578. }
  38579. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38580. };
  38581. Geometry.prototype._applyToMesh = function (mesh) {
  38582. var numOfMeshes = this._meshes.length;
  38583. // vertexBuffers
  38584. for (var kind in this._vertexBuffers) {
  38585. if (numOfMeshes === 1) {
  38586. this._vertexBuffers[kind].create();
  38587. }
  38588. var buffer = this._vertexBuffers[kind].getBuffer();
  38589. if (buffer)
  38590. buffer.references = numOfMeshes;
  38591. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38592. if (!this._extend) {
  38593. this._updateExtend();
  38594. }
  38595. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38596. mesh._createGlobalSubMesh(false);
  38597. //bounding info was just created again, world matrix should be applied again.
  38598. mesh._updateBoundingInfo();
  38599. }
  38600. }
  38601. // indexBuffer
  38602. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38603. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38604. }
  38605. if (this._indexBuffer) {
  38606. this._indexBuffer.references = numOfMeshes;
  38607. }
  38608. };
  38609. Geometry.prototype.notifyUpdate = function (kind) {
  38610. if (this.onGeometryUpdated) {
  38611. this.onGeometryUpdated(this, kind);
  38612. }
  38613. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38614. var mesh = _a[_i];
  38615. mesh._markSubMeshesAsAttributesDirty();
  38616. }
  38617. };
  38618. /**
  38619. * Load the geometry if it was flagged as delay loaded
  38620. * @param scene defines the hosting scene
  38621. * @param onLoaded defines a callback called when the geometry is loaded
  38622. */
  38623. Geometry.prototype.load = function (scene, onLoaded) {
  38624. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38625. return;
  38626. }
  38627. if (this.isReady()) {
  38628. if (onLoaded) {
  38629. onLoaded();
  38630. }
  38631. return;
  38632. }
  38633. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38634. this._queueLoad(scene, onLoaded);
  38635. };
  38636. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38637. var _this = this;
  38638. if (!this.delayLoadingFile) {
  38639. return;
  38640. }
  38641. scene._addPendingData(this);
  38642. scene._loadFile(this.delayLoadingFile, function (data) {
  38643. if (!_this._delayLoadingFunction) {
  38644. return;
  38645. }
  38646. _this._delayLoadingFunction(JSON.parse(data), _this);
  38647. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38648. _this._delayInfo = [];
  38649. scene._removePendingData(_this);
  38650. var meshes = _this._meshes;
  38651. var numOfMeshes = meshes.length;
  38652. for (var index = 0; index < numOfMeshes; index++) {
  38653. _this._applyToMesh(meshes[index]);
  38654. }
  38655. if (onLoaded) {
  38656. onLoaded();
  38657. }
  38658. }, undefined, true);
  38659. };
  38660. /**
  38661. * Invert the geometry to move from a right handed system to a left handed one.
  38662. */
  38663. Geometry.prototype.toLeftHanded = function () {
  38664. // Flip faces
  38665. var tIndices = this.getIndices(false);
  38666. if (tIndices != null && tIndices.length > 0) {
  38667. for (var i = 0; i < tIndices.length; i += 3) {
  38668. var tTemp = tIndices[i + 0];
  38669. tIndices[i + 0] = tIndices[i + 2];
  38670. tIndices[i + 2] = tTemp;
  38671. }
  38672. this.setIndices(tIndices);
  38673. }
  38674. // Negate position.z
  38675. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38676. if (tPositions != null && tPositions.length > 0) {
  38677. for (var i = 0; i < tPositions.length; i += 3) {
  38678. tPositions[i + 2] = -tPositions[i + 2];
  38679. }
  38680. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38681. }
  38682. // Negate normal.z
  38683. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38684. if (tNormals != null && tNormals.length > 0) {
  38685. for (var i = 0; i < tNormals.length; i += 3) {
  38686. tNormals[i + 2] = -tNormals[i + 2];
  38687. }
  38688. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38689. }
  38690. };
  38691. // Cache
  38692. /** @ignore */
  38693. Geometry.prototype._resetPointsArrayCache = function () {
  38694. this._positions = null;
  38695. };
  38696. /** @ignore */
  38697. Geometry.prototype._generatePointsArray = function () {
  38698. if (this._positions)
  38699. return true;
  38700. this._positions = [];
  38701. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38702. if (!data) {
  38703. return false;
  38704. }
  38705. for (var index = 0; index < data.length; index += 3) {
  38706. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38707. }
  38708. return true;
  38709. };
  38710. /**
  38711. * Gets a value indicating if the geometry is disposed
  38712. * @returns true if the geometry was disposed
  38713. */
  38714. Geometry.prototype.isDisposed = function () {
  38715. return this._isDisposed;
  38716. };
  38717. Geometry.prototype._disposeVertexArrayObjects = function () {
  38718. if (this._vertexArrayObjects) {
  38719. for (var kind in this._vertexArrayObjects) {
  38720. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38721. }
  38722. this._vertexArrayObjects = {};
  38723. }
  38724. };
  38725. /**
  38726. * Free all associated resources
  38727. */
  38728. Geometry.prototype.dispose = function () {
  38729. var meshes = this._meshes;
  38730. var numOfMeshes = meshes.length;
  38731. var index;
  38732. for (index = 0; index < numOfMeshes; index++) {
  38733. this.releaseForMesh(meshes[index]);
  38734. }
  38735. this._meshes = [];
  38736. this._disposeVertexArrayObjects();
  38737. for (var kind in this._vertexBuffers) {
  38738. this._vertexBuffers[kind].dispose();
  38739. }
  38740. this._vertexBuffers = {};
  38741. this._totalVertices = 0;
  38742. if (this._indexBuffer) {
  38743. this._engine._releaseBuffer(this._indexBuffer);
  38744. }
  38745. this._indexBuffer = null;
  38746. this._indices = [];
  38747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38748. this.delayLoadingFile = null;
  38749. this._delayLoadingFunction = null;
  38750. this._delayInfo = [];
  38751. this._boundingInfo = null;
  38752. this._scene.removeGeometry(this);
  38753. this._isDisposed = true;
  38754. };
  38755. /**
  38756. * Clone the current geometry into a new geometry
  38757. * @param id defines the unique ID of the new geometry
  38758. * @returns a new geometry object
  38759. */
  38760. Geometry.prototype.copy = function (id) {
  38761. var vertexData = new BABYLON.VertexData();
  38762. vertexData.indices = [];
  38763. var indices = this.getIndices();
  38764. if (indices) {
  38765. for (var index = 0; index < indices.length; index++) {
  38766. vertexData.indices.push(indices[index]);
  38767. }
  38768. }
  38769. var updatable = false;
  38770. var stopChecking = false;
  38771. var kind;
  38772. for (kind in this._vertexBuffers) {
  38773. // using slice() to make a copy of the array and not just reference it
  38774. var data = this.getVerticesData(kind);
  38775. if (data instanceof Float32Array) {
  38776. vertexData.set(new Float32Array(data), kind);
  38777. }
  38778. else {
  38779. vertexData.set(data.slice(0), kind);
  38780. }
  38781. if (!stopChecking) {
  38782. var vb = this.getVertexBuffer(kind);
  38783. if (vb) {
  38784. updatable = vb.isUpdatable();
  38785. stopChecking = !updatable;
  38786. }
  38787. }
  38788. }
  38789. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38790. geometry.delayLoadState = this.delayLoadState;
  38791. geometry.delayLoadingFile = this.delayLoadingFile;
  38792. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38793. for (kind in this._delayInfo) {
  38794. geometry._delayInfo = geometry._delayInfo || [];
  38795. geometry._delayInfo.push(kind);
  38796. }
  38797. // Bounding info
  38798. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38799. return geometry;
  38800. };
  38801. /**
  38802. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38803. * @return a JSON representation of the current geometry data (without the vertices data)
  38804. */
  38805. Geometry.prototype.serialize = function () {
  38806. var serializationObject = {};
  38807. serializationObject.id = this.id;
  38808. serializationObject.updatable = this._updatable;
  38809. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38810. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38811. }
  38812. return serializationObject;
  38813. };
  38814. Geometry.prototype.toNumberArray = function (origin) {
  38815. if (Array.isArray(origin)) {
  38816. return origin;
  38817. }
  38818. else {
  38819. return Array.prototype.slice.call(origin);
  38820. }
  38821. };
  38822. /**
  38823. * Serialize all vertices data into a JSON oject
  38824. * @returns a JSON representation of the current geometry data
  38825. */
  38826. Geometry.prototype.serializeVerticeData = function () {
  38827. var serializationObject = this.serialize();
  38828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38829. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38831. serializationObject.positions._updatable = true;
  38832. }
  38833. }
  38834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38835. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38836. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38837. serializationObject.normals._updatable = true;
  38838. }
  38839. }
  38840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38841. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38842. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38843. serializationObject.tangets._updatable = true;
  38844. }
  38845. }
  38846. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38847. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38848. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38849. serializationObject.uvs._updatable = true;
  38850. }
  38851. }
  38852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38853. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38854. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38855. serializationObject.uv2s._updatable = true;
  38856. }
  38857. }
  38858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38859. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38860. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38861. serializationObject.uv3s._updatable = true;
  38862. }
  38863. }
  38864. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38865. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38866. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38867. serializationObject.uv4s._updatable = true;
  38868. }
  38869. }
  38870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38871. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38872. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38873. serializationObject.uv5s._updatable = true;
  38874. }
  38875. }
  38876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38877. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38878. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38879. serializationObject.uv6s._updatable = true;
  38880. }
  38881. }
  38882. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38883. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38884. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38885. serializationObject.colors._updatable = true;
  38886. }
  38887. }
  38888. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38889. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38890. serializationObject.matricesIndices._isExpanded = true;
  38891. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38892. serializationObject.matricesIndices._updatable = true;
  38893. }
  38894. }
  38895. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38896. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38897. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38898. serializationObject.matricesWeights._updatable = true;
  38899. }
  38900. }
  38901. serializationObject.indices = this.toNumberArray(this.getIndices());
  38902. return serializationObject;
  38903. };
  38904. // Statics
  38905. /**
  38906. * Extracts a clone of a mesh geometry
  38907. * @param mesh defines the source mesh
  38908. * @param id defines the unique ID of the new geometry object
  38909. * @returns the new geometry object
  38910. */
  38911. Geometry.ExtractFromMesh = function (mesh, id) {
  38912. var geometry = mesh._geometry;
  38913. if (!geometry) {
  38914. return null;
  38915. }
  38916. return geometry.copy(id);
  38917. };
  38918. /**
  38919. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38920. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38921. * Be aware Math.random() could cause collisions, but:
  38922. * "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"
  38923. * @returns a string containing a new GUID
  38924. */
  38925. Geometry.RandomId = function () {
  38926. return BABYLON.Tools.RandomId();
  38927. };
  38928. /** @ignore */
  38929. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38930. var scene = mesh.getScene();
  38931. // Geometry
  38932. var geometryId = parsedGeometry.geometryId;
  38933. if (geometryId) {
  38934. var geometry = scene.getGeometryByID(geometryId);
  38935. if (geometry) {
  38936. geometry.applyToMesh(mesh);
  38937. }
  38938. }
  38939. else if (parsedGeometry instanceof ArrayBuffer) {
  38940. var binaryInfo = mesh._binaryInfo;
  38941. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38942. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38943. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38944. }
  38945. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38946. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38947. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38948. }
  38949. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38950. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38951. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38952. }
  38953. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38954. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38955. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38956. }
  38957. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38958. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38959. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38960. }
  38961. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38962. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38963. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38964. }
  38965. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38966. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38967. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38968. }
  38969. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38970. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38971. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38972. }
  38973. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38974. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38975. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38976. }
  38977. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38978. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38979. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38980. }
  38981. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38982. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38984. }
  38985. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38986. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38988. }
  38989. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38990. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38991. mesh.setIndices(indicesData, null);
  38992. }
  38993. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38994. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38995. mesh.subMeshes = [];
  38996. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38997. var materialIndex = subMeshesData[(i * 5) + 0];
  38998. var verticesStart = subMeshesData[(i * 5) + 1];
  38999. var verticesCount = subMeshesData[(i * 5) + 2];
  39000. var indexStart = subMeshesData[(i * 5) + 3];
  39001. var indexCount = subMeshesData[(i * 5) + 4];
  39002. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39003. }
  39004. }
  39005. }
  39006. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39007. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39008. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39009. if (parsedGeometry.tangents) {
  39010. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39011. }
  39012. if (parsedGeometry.uvs) {
  39013. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39014. }
  39015. if (parsedGeometry.uvs2) {
  39016. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39017. }
  39018. if (parsedGeometry.uvs3) {
  39019. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39020. }
  39021. if (parsedGeometry.uvs4) {
  39022. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39023. }
  39024. if (parsedGeometry.uvs5) {
  39025. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39026. }
  39027. if (parsedGeometry.uvs6) {
  39028. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39029. }
  39030. if (parsedGeometry.colors) {
  39031. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39032. }
  39033. if (parsedGeometry.matricesIndices) {
  39034. if (!parsedGeometry.matricesIndices._isExpanded) {
  39035. var floatIndices = [];
  39036. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39037. var matricesIndex = parsedGeometry.matricesIndices[i];
  39038. floatIndices.push(matricesIndex & 0x000000FF);
  39039. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39040. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39041. floatIndices.push(matricesIndex >> 24);
  39042. }
  39043. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39044. }
  39045. else {
  39046. delete parsedGeometry.matricesIndices._isExpanded;
  39047. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39048. }
  39049. }
  39050. if (parsedGeometry.matricesIndicesExtra) {
  39051. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39052. var floatIndices = [];
  39053. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39054. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39055. floatIndices.push(matricesIndex & 0x000000FF);
  39056. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39057. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39058. floatIndices.push(matricesIndex >> 24);
  39059. }
  39060. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39061. }
  39062. else {
  39063. delete parsedGeometry.matricesIndices._isExpanded;
  39064. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39065. }
  39066. }
  39067. if (parsedGeometry.matricesWeights) {
  39068. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39070. }
  39071. if (parsedGeometry.matricesWeightsExtra) {
  39072. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39073. }
  39074. mesh.setIndices(parsedGeometry.indices, null);
  39075. }
  39076. // SubMeshes
  39077. if (parsedGeometry.subMeshes) {
  39078. mesh.subMeshes = [];
  39079. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39080. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39081. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39082. }
  39083. }
  39084. // Flat shading
  39085. if (mesh._shouldGenerateFlatShading) {
  39086. mesh.convertToFlatShadedMesh();
  39087. delete mesh._shouldGenerateFlatShading;
  39088. }
  39089. // Update
  39090. mesh.computeWorldMatrix(true);
  39091. // Octree
  39092. var sceneOctree = scene.selectionOctree;
  39093. if (sceneOctree !== undefined && sceneOctree !== null) {
  39094. sceneOctree.addMesh(mesh);
  39095. }
  39096. };
  39097. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39098. var epsilon = 1e-3;
  39099. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39100. return;
  39101. }
  39102. var noInfluenceBoneIndex = 0.0;
  39103. if (parsedGeometry.skeletonId > -1) {
  39104. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39105. if (!skeleton) {
  39106. return;
  39107. }
  39108. noInfluenceBoneIndex = skeleton.bones.length;
  39109. }
  39110. else {
  39111. return;
  39112. }
  39113. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39114. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39115. var matricesWeights = parsedGeometry.matricesWeights;
  39116. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39117. var influencers = parsedGeometry.numBoneInfluencer;
  39118. var size = matricesWeights.length;
  39119. for (var i = 0; i < size; i += 4) {
  39120. var weight = 0.0;
  39121. var firstZeroWeight = -1;
  39122. for (var j = 0; j < 4; j++) {
  39123. var w = matricesWeights[i + j];
  39124. weight += w;
  39125. if (w < epsilon && firstZeroWeight < 0) {
  39126. firstZeroWeight = j;
  39127. }
  39128. }
  39129. if (matricesWeightsExtra) {
  39130. for (var j = 0; j < 4; j++) {
  39131. var w = matricesWeightsExtra[i + j];
  39132. weight += w;
  39133. if (w < epsilon && firstZeroWeight < 0) {
  39134. firstZeroWeight = j + 4;
  39135. }
  39136. }
  39137. }
  39138. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39139. firstZeroWeight = influencers - 1;
  39140. }
  39141. if (weight > epsilon) {
  39142. var mweight = 1.0 / weight;
  39143. for (var j = 0; j < 4; j++) {
  39144. matricesWeights[i + j] *= mweight;
  39145. }
  39146. if (matricesWeightsExtra) {
  39147. for (var j = 0; j < 4; j++) {
  39148. matricesWeightsExtra[i + j] *= mweight;
  39149. }
  39150. }
  39151. }
  39152. else {
  39153. if (firstZeroWeight >= 4) {
  39154. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39155. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39156. }
  39157. else {
  39158. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39159. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39160. }
  39161. }
  39162. }
  39163. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39164. if (parsedGeometry.matricesWeightsExtra) {
  39165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39166. }
  39167. };
  39168. /**
  39169. * Create a new geometry from persisted data (Using .babylon file format)
  39170. * @param parsedVertexData defines the persisted data
  39171. * @param scene defines the hosting scene
  39172. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39173. * @returns the new geometry object
  39174. */
  39175. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39176. if (scene.getGeometryByID(parsedVertexData.id)) {
  39177. return null; // null since geometry could be something else than a box...
  39178. }
  39179. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39180. if (BABYLON.Tags) {
  39181. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39182. }
  39183. if (parsedVertexData.delayLoadingFile) {
  39184. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39185. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39186. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39187. geometry._delayInfo = [];
  39188. if (parsedVertexData.hasUVs) {
  39189. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39190. }
  39191. if (parsedVertexData.hasUVs2) {
  39192. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39193. }
  39194. if (parsedVertexData.hasUVs3) {
  39195. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39196. }
  39197. if (parsedVertexData.hasUVs4) {
  39198. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39199. }
  39200. if (parsedVertexData.hasUVs5) {
  39201. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39202. }
  39203. if (parsedVertexData.hasUVs6) {
  39204. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39205. }
  39206. if (parsedVertexData.hasColors) {
  39207. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39208. }
  39209. if (parsedVertexData.hasMatricesIndices) {
  39210. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39211. }
  39212. if (parsedVertexData.hasMatricesWeights) {
  39213. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39214. }
  39215. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39216. }
  39217. else {
  39218. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39219. }
  39220. scene.pushGeometry(geometry, true);
  39221. return geometry;
  39222. };
  39223. return Geometry;
  39224. }());
  39225. BABYLON.Geometry = Geometry;
  39226. // Primitives
  39227. /// Abstract class
  39228. /**
  39229. * Abstract class used to provide common services for all typed geometries
  39230. */
  39231. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39232. __extends(_PrimitiveGeometry, _super);
  39233. /**
  39234. * Creates a new typed geometry
  39235. * @param id defines the unique ID of the geometry
  39236. * @param scene defines the hosting scene
  39237. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39238. * @param mesh defines the hosting mesh (can be null)
  39239. */
  39240. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39241. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39242. if (mesh === void 0) { mesh = null; }
  39243. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39244. _this._canBeRegenerated = _canBeRegenerated;
  39245. _this._beingRegenerated = true;
  39246. _this.regenerate();
  39247. _this._beingRegenerated = false;
  39248. return _this;
  39249. }
  39250. /**
  39251. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39252. * @returns true if the geometry can be regenerated
  39253. */
  39254. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39255. return this._canBeRegenerated;
  39256. };
  39257. /**
  39258. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39259. */
  39260. _PrimitiveGeometry.prototype.regenerate = function () {
  39261. if (!this._canBeRegenerated) {
  39262. return;
  39263. }
  39264. this._beingRegenerated = true;
  39265. this.setAllVerticesData(this._regenerateVertexData(), false);
  39266. this._beingRegenerated = false;
  39267. };
  39268. /**
  39269. * Clone the geometry
  39270. * @param id defines the unique ID of the new geometry
  39271. * @returns the new geometry
  39272. */
  39273. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39274. return _super.prototype.copy.call(this, id);
  39275. };
  39276. // overrides
  39277. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39278. if (!this._beingRegenerated) {
  39279. return;
  39280. }
  39281. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39282. };
  39283. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39284. if (!this._beingRegenerated) {
  39285. return;
  39286. }
  39287. _super.prototype.setVerticesData.call(this, kind, data, false);
  39288. };
  39289. // to override
  39290. /** @ignore */
  39291. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39292. throw new Error("Abstract method");
  39293. };
  39294. _PrimitiveGeometry.prototype.copy = function (id) {
  39295. throw new Error("Must be overriden in sub-classes.");
  39296. };
  39297. _PrimitiveGeometry.prototype.serialize = function () {
  39298. var serializationObject = _super.prototype.serialize.call(this);
  39299. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39300. return serializationObject;
  39301. };
  39302. return _PrimitiveGeometry;
  39303. }(Geometry));
  39304. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39305. /**
  39306. * Creates a ribbon geometry
  39307. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39308. */
  39309. var RibbonGeometry = /** @class */ (function (_super) {
  39310. __extends(RibbonGeometry, _super);
  39311. /**
  39312. * Creates a ribbon geometry
  39313. * @param id defines the unique ID of the geometry
  39314. * @param scene defines the hosting scene
  39315. * @param pathArray defines the array of paths to use
  39316. * @param closeArray defines if the last path and the first path must be joined
  39317. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39318. * @param offset defines the offset between points
  39319. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39320. * @param mesh defines the hosting mesh (can be null)
  39321. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39322. */
  39323. function RibbonGeometry(id, scene,
  39324. /**
  39325. * Defines the array of paths to use
  39326. */
  39327. pathArray,
  39328. /**
  39329. * Defines if the last and first points of each path in your pathArray must be joined
  39330. */
  39331. closeArray,
  39332. /**
  39333. * Defines if the last and first points of each path in your pathArray must be joined
  39334. */
  39335. closePath,
  39336. /**
  39337. * Defines the offset between points
  39338. */
  39339. offset, canBeRegenerated, mesh,
  39340. /**
  39341. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39342. */
  39343. side) {
  39344. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39345. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39346. _this.pathArray = pathArray;
  39347. _this.closeArray = closeArray;
  39348. _this.closePath = closePath;
  39349. _this.offset = offset;
  39350. _this.side = side;
  39351. return _this;
  39352. }
  39353. /** @ignore */
  39354. RibbonGeometry.prototype._regenerateVertexData = function () {
  39355. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39356. };
  39357. RibbonGeometry.prototype.copy = function (id) {
  39358. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39359. };
  39360. return RibbonGeometry;
  39361. }(_PrimitiveGeometry));
  39362. BABYLON.RibbonGeometry = RibbonGeometry;
  39363. /**
  39364. * Creates a box geometry
  39365. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39366. */
  39367. var BoxGeometry = /** @class */ (function (_super) {
  39368. __extends(BoxGeometry, _super);
  39369. /**
  39370. * Creates a box geometry
  39371. * @param id defines the unique ID of the geometry
  39372. * @param scene defines the hosting scene
  39373. * @param size defines the zise of the box (width, height and depth are the same)
  39374. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39375. * @param mesh defines the hosting mesh (can be null)
  39376. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39377. */
  39378. function BoxGeometry(id, scene,
  39379. /**
  39380. * Defines the zise of the box (width, height and depth are the same)
  39381. */
  39382. size, canBeRegenerated, mesh,
  39383. /**
  39384. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39385. */
  39386. side) {
  39387. if (mesh === void 0) { mesh = null; }
  39388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39390. _this.size = size;
  39391. _this.side = side;
  39392. return _this;
  39393. }
  39394. BoxGeometry.prototype._regenerateVertexData = function () {
  39395. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39396. };
  39397. BoxGeometry.prototype.copy = function (id) {
  39398. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39399. };
  39400. BoxGeometry.prototype.serialize = function () {
  39401. var serializationObject = _super.prototype.serialize.call(this);
  39402. serializationObject.size = this.size;
  39403. return serializationObject;
  39404. };
  39405. BoxGeometry.Parse = function (parsedBox, scene) {
  39406. if (scene.getGeometryByID(parsedBox.id)) {
  39407. return null; // null since geometry could be something else than a box...
  39408. }
  39409. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39410. if (BABYLON.Tags) {
  39411. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39412. }
  39413. scene.pushGeometry(box, true);
  39414. return box;
  39415. };
  39416. return BoxGeometry;
  39417. }(_PrimitiveGeometry));
  39418. BABYLON.BoxGeometry = BoxGeometry;
  39419. /**
  39420. * Creates a sphere geometry
  39421. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39422. */
  39423. var SphereGeometry = /** @class */ (function (_super) {
  39424. __extends(SphereGeometry, _super);
  39425. /**
  39426. * Create a new sphere geometry
  39427. * @param id defines the unique ID of the geometry
  39428. * @param scene defines the hosting scene
  39429. * @param segments defines the number of segments to use to create the sphere
  39430. * @param diameter defines the diameter of the sphere
  39431. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39432. * @param mesh defines the hosting mesh (can be null)
  39433. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39434. */
  39435. function SphereGeometry(id, scene,
  39436. /**
  39437. * Defines the number of segments to use to create the sphere
  39438. */
  39439. segments,
  39440. /**
  39441. * Defines the diameter of the sphere
  39442. */
  39443. diameter, canBeRegenerated, mesh,
  39444. /**
  39445. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39446. */
  39447. side) {
  39448. if (mesh === void 0) { mesh = null; }
  39449. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39450. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39451. _this.segments = segments;
  39452. _this.diameter = diameter;
  39453. _this.side = side;
  39454. return _this;
  39455. }
  39456. SphereGeometry.prototype._regenerateVertexData = function () {
  39457. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39458. };
  39459. SphereGeometry.prototype.copy = function (id) {
  39460. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39461. };
  39462. SphereGeometry.prototype.serialize = function () {
  39463. var serializationObject = _super.prototype.serialize.call(this);
  39464. serializationObject.segments = this.segments;
  39465. serializationObject.diameter = this.diameter;
  39466. return serializationObject;
  39467. };
  39468. SphereGeometry.Parse = function (parsedSphere, scene) {
  39469. if (scene.getGeometryByID(parsedSphere.id)) {
  39470. return null; // null since geometry could be something else than a sphere...
  39471. }
  39472. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39473. if (BABYLON.Tags) {
  39474. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39475. }
  39476. scene.pushGeometry(sphere, true);
  39477. return sphere;
  39478. };
  39479. return SphereGeometry;
  39480. }(_PrimitiveGeometry));
  39481. BABYLON.SphereGeometry = SphereGeometry;
  39482. /**
  39483. * Creates a disc geometry
  39484. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39485. */
  39486. var DiscGeometry = /** @class */ (function (_super) {
  39487. __extends(DiscGeometry, _super);
  39488. /**
  39489. * Creates a new disc geometry
  39490. * @param id defines the unique ID of the geometry
  39491. * @param scene defines the hosting scene
  39492. * @param radius defines the radius of the disc
  39493. * @param tessellation defines the tesselation factor to apply to the disc
  39494. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39495. * @param mesh defines the hosting mesh (can be null)
  39496. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39497. */
  39498. function DiscGeometry(id, scene,
  39499. /**
  39500. * Defines the radius of the disc
  39501. */
  39502. radius,
  39503. /**
  39504. * Defines the tesselation factor to apply to the disc
  39505. */
  39506. tessellation, canBeRegenerated, mesh,
  39507. /**
  39508. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39509. */
  39510. side) {
  39511. if (mesh === void 0) { mesh = null; }
  39512. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39513. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39514. _this.radius = radius;
  39515. _this.tessellation = tessellation;
  39516. _this.side = side;
  39517. return _this;
  39518. }
  39519. DiscGeometry.prototype._regenerateVertexData = function () {
  39520. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39521. };
  39522. DiscGeometry.prototype.copy = function (id) {
  39523. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39524. };
  39525. return DiscGeometry;
  39526. }(_PrimitiveGeometry));
  39527. BABYLON.DiscGeometry = DiscGeometry;
  39528. /**
  39529. * Creates a new cylinder geometry
  39530. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39531. */
  39532. var CylinderGeometry = /** @class */ (function (_super) {
  39533. __extends(CylinderGeometry, _super);
  39534. /**
  39535. * Creates a new cylinder geometry
  39536. * @param id defines the unique ID of the geometry
  39537. * @param scene defines the hosting scene
  39538. * @param height defines the height of the cylinder
  39539. * @param diameterTop defines the diameter of the cylinder's top cap
  39540. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39541. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39542. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39543. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39544. * @param mesh defines the hosting mesh (can be null)
  39545. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39546. */
  39547. function CylinderGeometry(id, scene,
  39548. /**
  39549. * Defines the height of the cylinder
  39550. */
  39551. height,
  39552. /**
  39553. * Defines the diameter of the cylinder's top cap
  39554. */
  39555. diameterTop,
  39556. /**
  39557. * Defines the diameter of the cylinder's bottom cap
  39558. */
  39559. diameterBottom,
  39560. /**
  39561. * Defines the tessellation factor to apply to the cylinder
  39562. */
  39563. tessellation,
  39564. /**
  39565. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39566. */
  39567. subdivisions, canBeRegenerated, mesh,
  39568. /**
  39569. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39570. */
  39571. side) {
  39572. if (subdivisions === void 0) { subdivisions = 1; }
  39573. if (mesh === void 0) { mesh = null; }
  39574. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39575. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39576. _this.height = height;
  39577. _this.diameterTop = diameterTop;
  39578. _this.diameterBottom = diameterBottom;
  39579. _this.tessellation = tessellation;
  39580. _this.subdivisions = subdivisions;
  39581. _this.side = side;
  39582. return _this;
  39583. }
  39584. CylinderGeometry.prototype._regenerateVertexData = function () {
  39585. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39586. };
  39587. CylinderGeometry.prototype.copy = function (id) {
  39588. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39589. };
  39590. CylinderGeometry.prototype.serialize = function () {
  39591. var serializationObject = _super.prototype.serialize.call(this);
  39592. serializationObject.height = this.height;
  39593. serializationObject.diameterTop = this.diameterTop;
  39594. serializationObject.diameterBottom = this.diameterBottom;
  39595. serializationObject.tessellation = this.tessellation;
  39596. return serializationObject;
  39597. };
  39598. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39599. if (scene.getGeometryByID(parsedCylinder.id)) {
  39600. return null; // null since geometry could be something else than a cylinder...
  39601. }
  39602. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39603. if (BABYLON.Tags) {
  39604. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39605. }
  39606. scene.pushGeometry(cylinder, true);
  39607. return cylinder;
  39608. };
  39609. return CylinderGeometry;
  39610. }(_PrimitiveGeometry));
  39611. BABYLON.CylinderGeometry = CylinderGeometry;
  39612. /**
  39613. * Creates a new torus geometry
  39614. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39615. */
  39616. var TorusGeometry = /** @class */ (function (_super) {
  39617. __extends(TorusGeometry, _super);
  39618. /**
  39619. * Creates a new torus geometry
  39620. * @param id defines the unique ID of the geometry
  39621. * @param scene defines the hosting scene
  39622. * @param diameter defines the diameter of the torus
  39623. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39624. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39625. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39626. * @param mesh defines the hosting mesh (can be null)
  39627. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39628. */
  39629. function TorusGeometry(id, scene,
  39630. /**
  39631. * Defines the diameter of the torus
  39632. */
  39633. diameter,
  39634. /**
  39635. * Defines the thickness of the torus (ie. internal diameter)
  39636. */
  39637. thickness,
  39638. /**
  39639. * Defines the tesselation factor to apply to the torus
  39640. */
  39641. tessellation, canBeRegenerated, mesh,
  39642. /**
  39643. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39644. */
  39645. side) {
  39646. if (mesh === void 0) { mesh = null; }
  39647. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39648. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39649. _this.diameter = diameter;
  39650. _this.thickness = thickness;
  39651. _this.tessellation = tessellation;
  39652. _this.side = side;
  39653. return _this;
  39654. }
  39655. TorusGeometry.prototype._regenerateVertexData = function () {
  39656. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39657. };
  39658. TorusGeometry.prototype.copy = function (id) {
  39659. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39660. };
  39661. TorusGeometry.prototype.serialize = function () {
  39662. var serializationObject = _super.prototype.serialize.call(this);
  39663. serializationObject.diameter = this.diameter;
  39664. serializationObject.thickness = this.thickness;
  39665. serializationObject.tessellation = this.tessellation;
  39666. return serializationObject;
  39667. };
  39668. TorusGeometry.Parse = function (parsedTorus, scene) {
  39669. if (scene.getGeometryByID(parsedTorus.id)) {
  39670. return null; // null since geometry could be something else than a torus...
  39671. }
  39672. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39673. if (BABYLON.Tags) {
  39674. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39675. }
  39676. scene.pushGeometry(torus, true);
  39677. return torus;
  39678. };
  39679. return TorusGeometry;
  39680. }(_PrimitiveGeometry));
  39681. BABYLON.TorusGeometry = TorusGeometry;
  39682. /**
  39683. * Creates a new ground geometry
  39684. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39685. */
  39686. var GroundGeometry = /** @class */ (function (_super) {
  39687. __extends(GroundGeometry, _super);
  39688. /**
  39689. * Creates a new ground geometry
  39690. * @param id defines the unique ID of the geometry
  39691. * @param scene defines the hosting scene
  39692. * @param width defines the width of the ground
  39693. * @param height defines the height of the ground
  39694. * @param subdivisions defines the subdivisions to apply to the ground
  39695. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39696. * @param mesh defines the hosting mesh (can be null)
  39697. */
  39698. function GroundGeometry(id, scene,
  39699. /**
  39700. * Defines the width of the ground
  39701. */
  39702. width,
  39703. /**
  39704. * Defines the height of the ground
  39705. */
  39706. height,
  39707. /**
  39708. * Defines the subdivisions to apply to the ground
  39709. */
  39710. subdivisions, canBeRegenerated, mesh) {
  39711. if (mesh === void 0) { mesh = null; }
  39712. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39713. _this.width = width;
  39714. _this.height = height;
  39715. _this.subdivisions = subdivisions;
  39716. return _this;
  39717. }
  39718. GroundGeometry.prototype._regenerateVertexData = function () {
  39719. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39720. };
  39721. GroundGeometry.prototype.copy = function (id) {
  39722. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39723. };
  39724. GroundGeometry.prototype.serialize = function () {
  39725. var serializationObject = _super.prototype.serialize.call(this);
  39726. serializationObject.width = this.width;
  39727. serializationObject.height = this.height;
  39728. serializationObject.subdivisions = this.subdivisions;
  39729. return serializationObject;
  39730. };
  39731. GroundGeometry.Parse = function (parsedGround, scene) {
  39732. if (scene.getGeometryByID(parsedGround.id)) {
  39733. return null; // null since geometry could be something else than a ground...
  39734. }
  39735. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39736. if (BABYLON.Tags) {
  39737. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39738. }
  39739. scene.pushGeometry(ground, true);
  39740. return ground;
  39741. };
  39742. return GroundGeometry;
  39743. }(_PrimitiveGeometry));
  39744. BABYLON.GroundGeometry = GroundGeometry;
  39745. /**
  39746. * Creates a tiled ground geometry
  39747. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39748. */
  39749. var TiledGroundGeometry = /** @class */ (function (_super) {
  39750. __extends(TiledGroundGeometry, _super);
  39751. /**
  39752. * Creates a tiled ground geometry
  39753. * @param id defines the unique ID of the geometry
  39754. * @param scene defines the hosting scene
  39755. * @param xmin defines the minimum value on X axis
  39756. * @param zmin defines the minimum value on Z axis
  39757. * @param xmax defines the maximum value on X axis
  39758. * @param zmax defines the maximum value on Z axis
  39759. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39760. * @param precision defines the precision to use when computing the tiles
  39761. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39762. * @param mesh defines the hosting mesh (can be null)
  39763. */
  39764. function TiledGroundGeometry(id, scene,
  39765. /**
  39766. * Defines the minimum value on X axis
  39767. */
  39768. xmin,
  39769. /**
  39770. * Defines the minimum value on Z axis
  39771. */
  39772. zmin,
  39773. /**
  39774. * Defines the maximum value on X axis
  39775. */
  39776. xmax,
  39777. /**
  39778. * Defines the maximum value on Z axis
  39779. */
  39780. zmax,
  39781. /**
  39782. * Defines the subdivisions to apply to the ground
  39783. */
  39784. subdivisions,
  39785. /**
  39786. * Defines the precision to use when computing the tiles
  39787. */
  39788. precision, canBeRegenerated, mesh) {
  39789. if (mesh === void 0) { mesh = null; }
  39790. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39791. _this.xmin = xmin;
  39792. _this.zmin = zmin;
  39793. _this.xmax = xmax;
  39794. _this.zmax = zmax;
  39795. _this.subdivisions = subdivisions;
  39796. _this.precision = precision;
  39797. return _this;
  39798. }
  39799. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39800. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39801. };
  39802. TiledGroundGeometry.prototype.copy = function (id) {
  39803. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39804. };
  39805. return TiledGroundGeometry;
  39806. }(_PrimitiveGeometry));
  39807. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39808. /**
  39809. * Creates a plane geometry
  39810. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39811. */
  39812. var PlaneGeometry = /** @class */ (function (_super) {
  39813. __extends(PlaneGeometry, _super);
  39814. /**
  39815. * Creates a plane geometry
  39816. * @param id defines the unique ID of the geometry
  39817. * @param scene defines the hosting scene
  39818. * @param size defines the size of the plane (width === height)
  39819. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39820. * @param mesh defines the hosting mesh (can be null)
  39821. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39822. */
  39823. function PlaneGeometry(id, scene,
  39824. /**
  39825. * Defines the size of the plane (width === height)
  39826. */
  39827. size, canBeRegenerated, mesh,
  39828. /**
  39829. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39830. */
  39831. side) {
  39832. if (mesh === void 0) { mesh = null; }
  39833. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39834. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39835. _this.size = size;
  39836. _this.side = side;
  39837. return _this;
  39838. }
  39839. PlaneGeometry.prototype._regenerateVertexData = function () {
  39840. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39841. };
  39842. PlaneGeometry.prototype.copy = function (id) {
  39843. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39844. };
  39845. PlaneGeometry.prototype.serialize = function () {
  39846. var serializationObject = _super.prototype.serialize.call(this);
  39847. serializationObject.size = this.size;
  39848. return serializationObject;
  39849. };
  39850. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39851. if (scene.getGeometryByID(parsedPlane.id)) {
  39852. return null; // null since geometry could be something else than a ground...
  39853. }
  39854. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39855. if (BABYLON.Tags) {
  39856. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39857. }
  39858. scene.pushGeometry(plane, true);
  39859. return plane;
  39860. };
  39861. return PlaneGeometry;
  39862. }(_PrimitiveGeometry));
  39863. BABYLON.PlaneGeometry = PlaneGeometry;
  39864. /**
  39865. * Creates a torus knot geometry
  39866. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39867. */
  39868. var TorusKnotGeometry = /** @class */ (function (_super) {
  39869. __extends(TorusKnotGeometry, _super);
  39870. /**
  39871. * Creates a torus knot geometry
  39872. * @param id defines the unique ID of the geometry
  39873. * @param scene defines the hosting scene
  39874. * @param radius defines the radius of the torus knot
  39875. * @param tube defines the thickness of the torus knot tube
  39876. * @param radialSegments defines the number of radial segments
  39877. * @param tubularSegments defines the number of tubular segments
  39878. * @param p defines the first number of windings
  39879. * @param q defines the second number of windings
  39880. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39881. * @param mesh defines the hosting mesh (can be null)
  39882. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39883. */
  39884. function TorusKnotGeometry(id, scene,
  39885. /**
  39886. * Defines the radius of the torus knot
  39887. */
  39888. radius,
  39889. /**
  39890. * Defines the thickness of the torus knot tube
  39891. */
  39892. tube,
  39893. /**
  39894. * Defines the number of radial segments
  39895. */
  39896. radialSegments,
  39897. /**
  39898. * Defines the number of tubular segments
  39899. */
  39900. tubularSegments,
  39901. /**
  39902. * Defines the first number of windings
  39903. */
  39904. p,
  39905. /**
  39906. * Defines the second number of windings
  39907. */
  39908. q, canBeRegenerated, mesh,
  39909. /**
  39910. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39911. */
  39912. side) {
  39913. if (mesh === void 0) { mesh = null; }
  39914. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39915. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39916. _this.radius = radius;
  39917. _this.tube = tube;
  39918. _this.radialSegments = radialSegments;
  39919. _this.tubularSegments = tubularSegments;
  39920. _this.p = p;
  39921. _this.q = q;
  39922. _this.side = side;
  39923. return _this;
  39924. }
  39925. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39926. 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 });
  39927. };
  39928. TorusKnotGeometry.prototype.copy = function (id) {
  39929. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39930. };
  39931. TorusKnotGeometry.prototype.serialize = function () {
  39932. var serializationObject = _super.prototype.serialize.call(this);
  39933. serializationObject.radius = this.radius;
  39934. serializationObject.tube = this.tube;
  39935. serializationObject.radialSegments = this.radialSegments;
  39936. serializationObject.tubularSegments = this.tubularSegments;
  39937. serializationObject.p = this.p;
  39938. serializationObject.q = this.q;
  39939. return serializationObject;
  39940. };
  39941. ;
  39942. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39943. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39944. return null; // null since geometry could be something else than a ground...
  39945. }
  39946. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39947. if (BABYLON.Tags) {
  39948. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39949. }
  39950. scene.pushGeometry(torusKnot, true);
  39951. return torusKnot;
  39952. };
  39953. return TorusKnotGeometry;
  39954. }(_PrimitiveGeometry));
  39955. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39956. //}
  39957. })(BABYLON || (BABYLON = {}));
  39958. //# sourceMappingURL=babylon.geometry.js.map
  39959. var BABYLON;
  39960. (function (BABYLON) {
  39961. /**
  39962. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39963. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39964. */
  39965. var PostProcessManager = /** @class */ (function () {
  39966. /**
  39967. * Creates a new instance PostProcess
  39968. * @param scene The scene that the post process is associated with.
  39969. */
  39970. function PostProcessManager(scene) {
  39971. this._vertexBuffers = {};
  39972. this._scene = scene;
  39973. }
  39974. PostProcessManager.prototype._prepareBuffers = function () {
  39975. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39976. return;
  39977. }
  39978. // VBO
  39979. var vertices = [];
  39980. vertices.push(1, 1);
  39981. vertices.push(-1, 1);
  39982. vertices.push(-1, -1);
  39983. vertices.push(1, -1);
  39984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39985. this._buildIndexBuffer();
  39986. };
  39987. PostProcessManager.prototype._buildIndexBuffer = function () {
  39988. // Indices
  39989. var indices = [];
  39990. indices.push(0);
  39991. indices.push(1);
  39992. indices.push(2);
  39993. indices.push(0);
  39994. indices.push(2);
  39995. indices.push(3);
  39996. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39997. };
  39998. /**
  39999. * Rebuilds the vertex buffers of the manager.
  40000. */
  40001. PostProcessManager.prototype._rebuild = function () {
  40002. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40003. if (!vb) {
  40004. return;
  40005. }
  40006. vb._rebuild();
  40007. this._buildIndexBuffer();
  40008. };
  40009. // Methods
  40010. /**
  40011. * Prepares a frame to be run through a post process.
  40012. * @param sourceTexture The input texture to the post procesess. (default: null)
  40013. * @param postProcesses An array of post processes to be run. (default: null)
  40014. * @returns True if the post processes were able to be run.
  40015. */
  40016. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40017. if (sourceTexture === void 0) { sourceTexture = null; }
  40018. if (postProcesses === void 0) { postProcesses = null; }
  40019. var camera = this._scene.activeCamera;
  40020. if (!camera) {
  40021. return false;
  40022. }
  40023. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40024. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40025. return false;
  40026. }
  40027. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40028. return true;
  40029. };
  40030. /**
  40031. * Manually render a set of post processes to a texture.
  40032. * @param postProcesses An array of post processes to be run.
  40033. * @param targetTexture The target texture to render to.
  40034. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40035. */
  40036. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40037. if (targetTexture === void 0) { targetTexture = null; }
  40038. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40039. var engine = this._scene.getEngine();
  40040. for (var index = 0; index < postProcesses.length; index++) {
  40041. if (index < postProcesses.length - 1) {
  40042. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40043. }
  40044. else {
  40045. if (targetTexture) {
  40046. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40047. }
  40048. else {
  40049. engine.restoreDefaultFramebuffer();
  40050. }
  40051. }
  40052. var pp = postProcesses[index];
  40053. var effect = pp.apply();
  40054. if (effect) {
  40055. pp.onBeforeRenderObservable.notifyObservers(effect);
  40056. // VBOs
  40057. this._prepareBuffers();
  40058. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40059. // Draw order
  40060. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40061. pp.onAfterRenderObservable.notifyObservers(effect);
  40062. }
  40063. }
  40064. // Restore depth buffer
  40065. engine.setDepthBuffer(true);
  40066. engine.setDepthWrite(true);
  40067. };
  40068. /**
  40069. * Finalize the result of the output of the postprocesses.
  40070. * @param doNotPresent If true the result will not be displayed to the screen.
  40071. * @param targetTexture The target texture to render to.
  40072. * @param faceIndex The index of the face to bind the target texture to.
  40073. * @param postProcesses The array of post processes to render.
  40074. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40075. */
  40076. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40077. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40078. var camera = this._scene.activeCamera;
  40079. if (!camera) {
  40080. return;
  40081. }
  40082. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40083. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40084. return;
  40085. }
  40086. var engine = this._scene.getEngine();
  40087. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40088. var pp = postProcesses[index];
  40089. if (index < len - 1) {
  40090. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40091. }
  40092. else {
  40093. if (targetTexture) {
  40094. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40095. pp._outputTexture = targetTexture;
  40096. }
  40097. else {
  40098. engine.restoreDefaultFramebuffer();
  40099. pp._outputTexture = null;
  40100. }
  40101. }
  40102. if (doNotPresent) {
  40103. break;
  40104. }
  40105. var effect = pp.apply();
  40106. if (effect) {
  40107. pp.onBeforeRenderObservable.notifyObservers(effect);
  40108. // VBOs
  40109. this._prepareBuffers();
  40110. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40111. // Draw order
  40112. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40113. pp.onAfterRenderObservable.notifyObservers(effect);
  40114. }
  40115. }
  40116. // Restore states
  40117. engine.setDepthBuffer(true);
  40118. engine.setDepthWrite(true);
  40119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40120. };
  40121. /**
  40122. * Disposes of the post process manager.
  40123. */
  40124. PostProcessManager.prototype.dispose = function () {
  40125. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40126. if (buffer) {
  40127. buffer.dispose();
  40128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40129. }
  40130. if (this._indexBuffer) {
  40131. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40132. this._indexBuffer = null;
  40133. }
  40134. };
  40135. return PostProcessManager;
  40136. }());
  40137. BABYLON.PostProcessManager = PostProcessManager;
  40138. })(BABYLON || (BABYLON = {}));
  40139. //# sourceMappingURL=babylon.postProcessManager.js.map
  40140. var BABYLON;
  40141. (function (BABYLON) {
  40142. /**
  40143. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40144. */
  40145. var PerformanceMonitor = /** @class */ (function () {
  40146. /**
  40147. * constructor
  40148. * @param frameSampleSize The number of samples required to saturate the sliding window
  40149. */
  40150. function PerformanceMonitor(frameSampleSize) {
  40151. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40152. this._enabled = true;
  40153. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40154. }
  40155. /**
  40156. * Samples current frame
  40157. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40158. */
  40159. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40160. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40161. if (!this._enabled)
  40162. return;
  40163. if (this._lastFrameTimeMs != null) {
  40164. var dt = timeMs - this._lastFrameTimeMs;
  40165. this._rollingFrameTime.add(dt);
  40166. }
  40167. this._lastFrameTimeMs = timeMs;
  40168. };
  40169. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40170. /**
  40171. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40172. * @return Average frame time in milliseconds
  40173. */
  40174. get: function () {
  40175. return this._rollingFrameTime.average;
  40176. },
  40177. enumerable: true,
  40178. configurable: true
  40179. });
  40180. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40181. /**
  40182. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40183. * @return Frame time variance in milliseconds squared
  40184. */
  40185. get: function () {
  40186. return this._rollingFrameTime.variance;
  40187. },
  40188. enumerable: true,
  40189. configurable: true
  40190. });
  40191. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40192. /**
  40193. * Returns the frame time of the most recent frame
  40194. * @return Frame time in milliseconds
  40195. */
  40196. get: function () {
  40197. return this._rollingFrameTime.history(0);
  40198. },
  40199. enumerable: true,
  40200. configurable: true
  40201. });
  40202. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40203. /**
  40204. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40205. * @return Framerate in frames per second
  40206. */
  40207. get: function () {
  40208. return 1000.0 / this._rollingFrameTime.average;
  40209. },
  40210. enumerable: true,
  40211. configurable: true
  40212. });
  40213. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40214. /**
  40215. * Returns the average framerate in frames per second using the most recent frame time
  40216. * @return Framerate in frames per second
  40217. */
  40218. get: function () {
  40219. var history = this._rollingFrameTime.history(0);
  40220. if (history === 0) {
  40221. return 0;
  40222. }
  40223. return 1000.0 / history;
  40224. },
  40225. enumerable: true,
  40226. configurable: true
  40227. });
  40228. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40229. /**
  40230. * Returns true if enough samples have been taken to completely fill the sliding window
  40231. * @return true if saturated
  40232. */
  40233. get: function () {
  40234. return this._rollingFrameTime.isSaturated();
  40235. },
  40236. enumerable: true,
  40237. configurable: true
  40238. });
  40239. /**
  40240. * Enables contributions to the sliding window sample set
  40241. */
  40242. PerformanceMonitor.prototype.enable = function () {
  40243. this._enabled = true;
  40244. };
  40245. /**
  40246. * Disables contributions to the sliding window sample set
  40247. * Samples will not be interpolated over the disabled period
  40248. */
  40249. PerformanceMonitor.prototype.disable = function () {
  40250. this._enabled = false;
  40251. //clear last sample to avoid interpolating over the disabled period when next enabled
  40252. this._lastFrameTimeMs = null;
  40253. };
  40254. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40255. /**
  40256. * Returns true if sampling is enabled
  40257. * @return true if enabled
  40258. */
  40259. get: function () {
  40260. return this._enabled;
  40261. },
  40262. enumerable: true,
  40263. configurable: true
  40264. });
  40265. /**
  40266. * Resets performance monitor
  40267. */
  40268. PerformanceMonitor.prototype.reset = function () {
  40269. //clear last sample to avoid interpolating over the disabled period when next enabled
  40270. this._lastFrameTimeMs = null;
  40271. //wipe record
  40272. this._rollingFrameTime.reset();
  40273. };
  40274. return PerformanceMonitor;
  40275. }());
  40276. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40277. /**
  40278. * RollingAverage
  40279. *
  40280. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40281. */
  40282. var RollingAverage = /** @class */ (function () {
  40283. /**
  40284. * constructor
  40285. * @param length The number of samples required to saturate the sliding window
  40286. */
  40287. function RollingAverage(length) {
  40288. this._samples = new Array(length);
  40289. this.reset();
  40290. }
  40291. /**
  40292. * Adds a sample to the sample set
  40293. * @param v The sample value
  40294. */
  40295. RollingAverage.prototype.add = function (v) {
  40296. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40297. var delta;
  40298. //we need to check if we've already wrapped round
  40299. if (this.isSaturated()) {
  40300. //remove bottom of stack from mean
  40301. var bottomValue = this._samples[this._pos];
  40302. delta = bottomValue - this.average;
  40303. this.average -= delta / (this._sampleCount - 1);
  40304. this._m2 -= delta * (bottomValue - this.average);
  40305. }
  40306. else {
  40307. this._sampleCount++;
  40308. }
  40309. //add new value to mean
  40310. delta = v - this.average;
  40311. this.average += delta / (this._sampleCount);
  40312. this._m2 += delta * (v - this.average);
  40313. //set the new variance
  40314. this.variance = this._m2 / (this._sampleCount - 1);
  40315. this._samples[this._pos] = v;
  40316. this._pos++;
  40317. this._pos %= this._samples.length; //positive wrap around
  40318. };
  40319. /**
  40320. * Returns previously added values or null if outside of history or outside the sliding window domain
  40321. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40322. * @return Value previously recorded with add() or null if outside of range
  40323. */
  40324. RollingAverage.prototype.history = function (i) {
  40325. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40326. return 0;
  40327. }
  40328. var i0 = this._wrapPosition(this._pos - 1.0);
  40329. return this._samples[this._wrapPosition(i0 - i)];
  40330. };
  40331. /**
  40332. * Returns true if enough samples have been taken to completely fill the sliding window
  40333. * @return true if sample-set saturated
  40334. */
  40335. RollingAverage.prototype.isSaturated = function () {
  40336. return this._sampleCount >= this._samples.length;
  40337. };
  40338. /**
  40339. * Resets the rolling average (equivalent to 0 samples taken so far)
  40340. */
  40341. RollingAverage.prototype.reset = function () {
  40342. this.average = 0;
  40343. this.variance = 0;
  40344. this._sampleCount = 0;
  40345. this._pos = 0;
  40346. this._m2 = 0;
  40347. };
  40348. /**
  40349. * Wraps a value around the sample range boundaries
  40350. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40351. * @return Wrapped position in sample range
  40352. */
  40353. RollingAverage.prototype._wrapPosition = function (i) {
  40354. var max = this._samples.length;
  40355. return ((i % max) + max) % max;
  40356. };
  40357. return RollingAverage;
  40358. }());
  40359. BABYLON.RollingAverage = RollingAverage;
  40360. })(BABYLON || (BABYLON = {}));
  40361. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40362. var BABYLON;
  40363. (function (BABYLON) {
  40364. /**
  40365. * This groups together the common properties used for image processing either in direct forward pass
  40366. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40367. * or not.
  40368. */
  40369. var ImageProcessingConfiguration = /** @class */ (function () {
  40370. function ImageProcessingConfiguration() {
  40371. /**
  40372. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40373. */
  40374. this.colorCurves = new BABYLON.ColorCurves();
  40375. this._colorCurvesEnabled = false;
  40376. this._colorGradingEnabled = false;
  40377. this._colorGradingWithGreenDepth = true;
  40378. this._colorGradingBGR = true;
  40379. this._exposure = 1.0;
  40380. this._toneMappingEnabled = false;
  40381. this._contrast = 1.0;
  40382. /**
  40383. * Vignette stretch size.
  40384. */
  40385. this.vignetteStretch = 0;
  40386. /**
  40387. * Vignette centre X Offset.
  40388. */
  40389. this.vignetteCentreX = 0;
  40390. /**
  40391. * Vignette centre Y Offset.
  40392. */
  40393. this.vignetteCentreY = 0;
  40394. /**
  40395. * Vignette weight or intensity of the vignette effect.
  40396. */
  40397. this.vignetteWeight = 1.5;
  40398. /**
  40399. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40400. * if vignetteEnabled is set to true.
  40401. */
  40402. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40403. /**
  40404. * Camera field of view used by the Vignette effect.
  40405. */
  40406. this.vignetteCameraFov = 0.5;
  40407. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40408. this._vignetteEnabled = false;
  40409. this._applyByPostProcess = false;
  40410. this._isEnabled = true;
  40411. /**
  40412. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40413. */
  40414. this.onUpdateParameters = new BABYLON.Observable();
  40415. }
  40416. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40417. /**
  40418. * Gets wether the color curves effect is enabled.
  40419. */
  40420. get: function () {
  40421. return this._colorCurvesEnabled;
  40422. },
  40423. /**
  40424. * Sets wether the color curves effect is enabled.
  40425. */
  40426. set: function (value) {
  40427. if (this._colorCurvesEnabled === value) {
  40428. return;
  40429. }
  40430. this._colorCurvesEnabled = value;
  40431. this._updateParameters();
  40432. },
  40433. enumerable: true,
  40434. configurable: true
  40435. });
  40436. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40437. /**
  40438. * Gets wether the color grading effect is enabled.
  40439. */
  40440. get: function () {
  40441. return this._colorGradingEnabled;
  40442. },
  40443. /**
  40444. * Sets wether the color grading effect is enabled.
  40445. */
  40446. set: function (value) {
  40447. if (this._colorGradingEnabled === value) {
  40448. return;
  40449. }
  40450. this._colorGradingEnabled = value;
  40451. this._updateParameters();
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40457. /**
  40458. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40459. */
  40460. get: function () {
  40461. return this._colorGradingWithGreenDepth;
  40462. },
  40463. /**
  40464. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40465. */
  40466. set: function (value) {
  40467. if (this._colorGradingWithGreenDepth === value) {
  40468. return;
  40469. }
  40470. this._colorGradingWithGreenDepth = value;
  40471. this._updateParameters();
  40472. },
  40473. enumerable: true,
  40474. configurable: true
  40475. });
  40476. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40477. /**
  40478. * Gets wether the color grading texture contains BGR values.
  40479. */
  40480. get: function () {
  40481. return this._colorGradingBGR;
  40482. },
  40483. /**
  40484. * Sets wether the color grading texture contains BGR values.
  40485. */
  40486. set: function (value) {
  40487. if (this._colorGradingBGR === value) {
  40488. return;
  40489. }
  40490. this._colorGradingBGR = value;
  40491. this._updateParameters();
  40492. },
  40493. enumerable: true,
  40494. configurable: true
  40495. });
  40496. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40497. /**
  40498. * Gets the Exposure used in the effect.
  40499. */
  40500. get: function () {
  40501. return this._exposure;
  40502. },
  40503. /**
  40504. * Sets the Exposure used in the effect.
  40505. */
  40506. set: function (value) {
  40507. if (this._exposure === value) {
  40508. return;
  40509. }
  40510. this._exposure = value;
  40511. this._updateParameters();
  40512. },
  40513. enumerable: true,
  40514. configurable: true
  40515. });
  40516. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40517. /**
  40518. * Gets wether the tone mapping effect is enabled.
  40519. */
  40520. get: function () {
  40521. return this._toneMappingEnabled;
  40522. },
  40523. /**
  40524. * Sets wether the tone mapping effect is enabled.
  40525. */
  40526. set: function (value) {
  40527. if (this._toneMappingEnabled === value) {
  40528. return;
  40529. }
  40530. this._toneMappingEnabled = value;
  40531. this._updateParameters();
  40532. },
  40533. enumerable: true,
  40534. configurable: true
  40535. });
  40536. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40537. /**
  40538. * Gets the contrast used in the effect.
  40539. */
  40540. get: function () {
  40541. return this._contrast;
  40542. },
  40543. /**
  40544. * Sets the contrast used in the effect.
  40545. */
  40546. set: function (value) {
  40547. if (this._contrast === value) {
  40548. return;
  40549. }
  40550. this._contrast = value;
  40551. this._updateParameters();
  40552. },
  40553. enumerable: true,
  40554. configurable: true
  40555. });
  40556. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40557. /**
  40558. * Gets the vignette blend mode allowing different kind of effect.
  40559. */
  40560. get: function () {
  40561. return this._vignetteBlendMode;
  40562. },
  40563. /**
  40564. * Sets the vignette blend mode allowing different kind of effect.
  40565. */
  40566. set: function (value) {
  40567. if (this._vignetteBlendMode === value) {
  40568. return;
  40569. }
  40570. this._vignetteBlendMode = value;
  40571. this._updateParameters();
  40572. },
  40573. enumerable: true,
  40574. configurable: true
  40575. });
  40576. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40577. /**
  40578. * Gets wether the vignette effect is enabled.
  40579. */
  40580. get: function () {
  40581. return this._vignetteEnabled;
  40582. },
  40583. /**
  40584. * Sets wether the vignette effect is enabled.
  40585. */
  40586. set: function (value) {
  40587. if (this._vignetteEnabled === value) {
  40588. return;
  40589. }
  40590. this._vignetteEnabled = value;
  40591. this._updateParameters();
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40597. /**
  40598. * Gets wether the image processing is applied through a post process or not.
  40599. */
  40600. get: function () {
  40601. return this._applyByPostProcess;
  40602. },
  40603. /**
  40604. * Sets wether the image processing is applied through a post process or not.
  40605. */
  40606. set: function (value) {
  40607. if (this._applyByPostProcess === value) {
  40608. return;
  40609. }
  40610. this._applyByPostProcess = value;
  40611. this._updateParameters();
  40612. },
  40613. enumerable: true,
  40614. configurable: true
  40615. });
  40616. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40617. /**
  40618. * Gets wether the image processing is enabled or not.
  40619. */
  40620. get: function () {
  40621. return this._isEnabled;
  40622. },
  40623. /**
  40624. * Sets wether the image processing is enabled or not.
  40625. */
  40626. set: function (value) {
  40627. if (this._isEnabled === value) {
  40628. return;
  40629. }
  40630. this._isEnabled = value;
  40631. this._updateParameters();
  40632. },
  40633. enumerable: true,
  40634. configurable: true
  40635. });
  40636. /**
  40637. * Method called each time the image processing information changes requires to recompile the effect.
  40638. */
  40639. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40640. this.onUpdateParameters.notifyObservers(this);
  40641. };
  40642. ImageProcessingConfiguration.prototype.getClassName = function () {
  40643. return "ImageProcessingConfiguration";
  40644. };
  40645. /**
  40646. * Prepare the list of uniforms associated with the Image Processing effects.
  40647. * @param uniformsList The list of uniforms used in the effect
  40648. * @param defines the list of defines currently in use
  40649. */
  40650. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40651. if (defines.EXPOSURE) {
  40652. uniforms.push("exposureLinear");
  40653. }
  40654. if (defines.CONTRAST) {
  40655. uniforms.push("contrast");
  40656. }
  40657. if (defines.COLORGRADING) {
  40658. uniforms.push("colorTransformSettings");
  40659. }
  40660. if (defines.VIGNETTE) {
  40661. uniforms.push("vInverseScreenSize");
  40662. uniforms.push("vignetteSettings1");
  40663. uniforms.push("vignetteSettings2");
  40664. }
  40665. if (defines.COLORCURVES) {
  40666. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40667. }
  40668. };
  40669. /**
  40670. * Prepare the list of samplers associated with the Image Processing effects.
  40671. * @param uniformsList The list of uniforms used in the effect
  40672. * @param defines the list of defines currently in use
  40673. */
  40674. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40675. if (defines.COLORGRADING) {
  40676. samplersList.push("txColorTransform");
  40677. }
  40678. };
  40679. /**
  40680. * Prepare the list of defines associated to the shader.
  40681. * @param defines the list of defines to complete
  40682. */
  40683. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40684. if (forPostProcess === void 0) { forPostProcess = false; }
  40685. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40686. defines.VIGNETTE = false;
  40687. defines.TONEMAPPING = false;
  40688. defines.CONTRAST = false;
  40689. defines.EXPOSURE = false;
  40690. defines.COLORCURVES = false;
  40691. defines.COLORGRADING = false;
  40692. defines.COLORGRADING3D = false;
  40693. defines.IMAGEPROCESSING = false;
  40694. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40695. return;
  40696. }
  40697. defines.VIGNETTE = this.vignetteEnabled;
  40698. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40699. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40700. defines.TONEMAPPING = this.toneMappingEnabled;
  40701. defines.CONTRAST = (this.contrast !== 1.0);
  40702. defines.EXPOSURE = (this.exposure !== 1.0);
  40703. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40704. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40705. if (defines.COLORGRADING) {
  40706. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40707. }
  40708. else {
  40709. defines.COLORGRADING3D = false;
  40710. }
  40711. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40712. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40713. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40714. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40715. };
  40716. /**
  40717. * Returns true if all the image processing information are ready.
  40718. */
  40719. ImageProcessingConfiguration.prototype.isReady = function () {
  40720. // Color Grading texure can not be none blocking.
  40721. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40722. };
  40723. /**
  40724. * Binds the image processing to the shader.
  40725. * @param effect The effect to bind to
  40726. */
  40727. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40728. if (aspectRatio === void 0) { aspectRatio = 1; }
  40729. // Color Curves
  40730. if (this._colorCurvesEnabled && this.colorCurves) {
  40731. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40732. }
  40733. // Vignette
  40734. if (this._vignetteEnabled) {
  40735. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40736. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40737. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40738. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40739. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40740. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40741. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40742. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40743. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40744. var vignettePower = -2.0 * this.vignetteWeight;
  40745. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40746. }
  40747. // Exposure
  40748. effect.setFloat("exposureLinear", this.exposure);
  40749. // Contrast
  40750. effect.setFloat("contrast", this.contrast);
  40751. // Color transform settings
  40752. if (this.colorGradingTexture) {
  40753. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40754. var textureSize = this.colorGradingTexture.getSize().height;
  40755. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40756. 0.5 / textureSize, // textureOffset
  40757. textureSize, // textureSize
  40758. this.colorGradingTexture.level // weight
  40759. );
  40760. }
  40761. };
  40762. /**
  40763. * Clones the current image processing instance.
  40764. * @return The cloned image processing
  40765. */
  40766. ImageProcessingConfiguration.prototype.clone = function () {
  40767. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40768. };
  40769. /**
  40770. * Serializes the current image processing instance to a json representation.
  40771. * @return a JSON representation
  40772. */
  40773. ImageProcessingConfiguration.prototype.serialize = function () {
  40774. return BABYLON.SerializationHelper.Serialize(this);
  40775. };
  40776. /**
  40777. * Parses the image processing from a json representation.
  40778. * @param source the JSON source to parse
  40779. * @return The parsed image processing
  40780. */
  40781. ImageProcessingConfiguration.Parse = function (source) {
  40782. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40783. };
  40784. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40785. /**
  40786. * Used to apply the vignette as a mix with the pixel color.
  40787. */
  40788. get: function () {
  40789. return this._VIGNETTEMODE_MULTIPLY;
  40790. },
  40791. enumerable: true,
  40792. configurable: true
  40793. });
  40794. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40795. /**
  40796. * Used to apply the vignette as a replacement of the pixel color.
  40797. */
  40798. get: function () {
  40799. return this._VIGNETTEMODE_OPAQUE;
  40800. },
  40801. enumerable: true,
  40802. configurable: true
  40803. });
  40804. // Static constants associated to the image processing.
  40805. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40806. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40807. __decorate([
  40808. BABYLON.serializeAsColorCurves()
  40809. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40810. __decorate([
  40811. BABYLON.serialize()
  40812. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40813. __decorate([
  40814. BABYLON.serializeAsTexture()
  40815. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40816. __decorate([
  40817. BABYLON.serialize()
  40818. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40819. __decorate([
  40820. BABYLON.serialize()
  40821. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40822. __decorate([
  40823. BABYLON.serialize()
  40824. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40825. __decorate([
  40826. BABYLON.serialize()
  40827. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40828. __decorate([
  40829. BABYLON.serialize()
  40830. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40831. __decorate([
  40832. BABYLON.serialize()
  40833. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40834. __decorate([
  40835. BABYLON.serialize()
  40836. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40837. __decorate([
  40838. BABYLON.serialize()
  40839. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40840. __decorate([
  40841. BABYLON.serialize()
  40842. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40843. __decorate([
  40844. BABYLON.serialize()
  40845. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40846. __decorate([
  40847. BABYLON.serializeAsColor4()
  40848. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40849. __decorate([
  40850. BABYLON.serialize()
  40851. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40852. __decorate([
  40853. BABYLON.serialize()
  40854. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40855. __decorate([
  40856. BABYLON.serialize()
  40857. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40858. __decorate([
  40859. BABYLON.serialize()
  40860. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40861. __decorate([
  40862. BABYLON.serialize()
  40863. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40864. return ImageProcessingConfiguration;
  40865. }());
  40866. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40867. })(BABYLON || (BABYLON = {}));
  40868. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40869. var BABYLON;
  40870. (function (BABYLON) {
  40871. /**
  40872. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40873. * It can help converting any input color in a desired output one. This can then be used to create effects
  40874. * from sepia, black and white to sixties or futuristic rendering...
  40875. *
  40876. * The only supported format is currently 3dl.
  40877. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40878. */
  40879. var ColorGradingTexture = /** @class */ (function (_super) {
  40880. __extends(ColorGradingTexture, _super);
  40881. /**
  40882. * Instantiates a ColorGradingTexture from the following parameters.
  40883. *
  40884. * @param url The location of the color gradind data (currently only supporting 3dl)
  40885. * @param scene The scene the texture will be used in
  40886. */
  40887. function ColorGradingTexture(url, scene) {
  40888. var _this = _super.call(this, scene) || this;
  40889. if (!url) {
  40890. return _this;
  40891. }
  40892. _this._engine = scene.getEngine();
  40893. _this._textureMatrix = BABYLON.Matrix.Identity();
  40894. _this.name = url;
  40895. _this.url = url;
  40896. _this.hasAlpha = false;
  40897. _this.isCube = false;
  40898. _this.is3D = _this._engine.webGLVersion > 1;
  40899. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40900. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40901. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40902. _this.anisotropicFilteringLevel = 1;
  40903. _this._texture = _this._getFromCache(url, true);
  40904. if (!_this._texture) {
  40905. if (!scene.useDelayedTextureLoading) {
  40906. _this.loadTexture();
  40907. }
  40908. else {
  40909. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40910. }
  40911. }
  40912. return _this;
  40913. }
  40914. /**
  40915. * Returns the texture matrix used in most of the material.
  40916. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40917. */
  40918. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40919. return this._textureMatrix;
  40920. };
  40921. /**
  40922. * Occurs when the file being loaded is a .3dl LUT file.
  40923. */
  40924. ColorGradingTexture.prototype.load3dlTexture = function () {
  40925. var engine = this._engine;
  40926. var texture;
  40927. if (engine.webGLVersion === 1) {
  40928. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40929. }
  40930. else {
  40931. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40932. }
  40933. this._texture = texture;
  40934. var callback = function (text) {
  40935. if (typeof text !== "string") {
  40936. return;
  40937. }
  40938. var data = null;
  40939. var tempData = null;
  40940. var line;
  40941. var lines = text.split('\n');
  40942. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40943. var maxColor = 0;
  40944. for (var i = 0; i < lines.length; i++) {
  40945. line = lines[i];
  40946. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40947. continue;
  40948. if (line.indexOf('#') === 0)
  40949. continue;
  40950. var words = line.split(" ");
  40951. if (size === 0) {
  40952. // Number of space + one
  40953. size = words.length;
  40954. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40955. tempData = new Float32Array(size * size * size * 4);
  40956. continue;
  40957. }
  40958. if (size != 0) {
  40959. var r = Math.max(parseInt(words[0]), 0);
  40960. var g = Math.max(parseInt(words[1]), 0);
  40961. var b = Math.max(parseInt(words[2]), 0);
  40962. maxColor = Math.max(r, maxColor);
  40963. maxColor = Math.max(g, maxColor);
  40964. maxColor = Math.max(b, maxColor);
  40965. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40966. if (tempData) {
  40967. tempData[pixelStorageIndex + 0] = r;
  40968. tempData[pixelStorageIndex + 1] = g;
  40969. tempData[pixelStorageIndex + 2] = b;
  40970. }
  40971. pixelIndexSlice++;
  40972. if (pixelIndexSlice % size == 0) {
  40973. pixelIndexH++;
  40974. pixelIndexSlice = 0;
  40975. if (pixelIndexH % size == 0) {
  40976. pixelIndexW++;
  40977. pixelIndexH = 0;
  40978. }
  40979. }
  40980. }
  40981. }
  40982. if (tempData && data) {
  40983. for (var i = 0; i < tempData.length; i++) {
  40984. if (i > 0 && (i + 1) % 4 === 0) {
  40985. data[i] = 255;
  40986. }
  40987. else {
  40988. var value = tempData[i];
  40989. data[i] = (value / maxColor * 255);
  40990. }
  40991. }
  40992. }
  40993. if (texture.is3D) {
  40994. texture.updateSize(size, size, size);
  40995. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40996. }
  40997. else {
  40998. texture.updateSize(size * size, size);
  40999. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41000. }
  41001. };
  41002. var scene = this.getScene();
  41003. if (scene) {
  41004. scene._loadFile(this.url, callback);
  41005. }
  41006. else {
  41007. this._engine._loadFile(this.url, callback);
  41008. }
  41009. return this._texture;
  41010. };
  41011. /**
  41012. * Starts the loading process of the texture.
  41013. */
  41014. ColorGradingTexture.prototype.loadTexture = function () {
  41015. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41016. this.load3dlTexture();
  41017. }
  41018. };
  41019. /**
  41020. * Clones the color gradind texture.
  41021. */
  41022. ColorGradingTexture.prototype.clone = function () {
  41023. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41024. // Base texture
  41025. newTexture.level = this.level;
  41026. return newTexture;
  41027. };
  41028. /**
  41029. * Called during delayed load for textures.
  41030. */
  41031. ColorGradingTexture.prototype.delayLoad = function () {
  41032. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41033. return;
  41034. }
  41035. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41036. this._texture = this._getFromCache(this.url, true);
  41037. if (!this._texture) {
  41038. this.loadTexture();
  41039. }
  41040. };
  41041. /**
  41042. * Parses a color grading texture serialized by Babylon.
  41043. * @param parsedTexture The texture information being parsedTexture
  41044. * @param scene The scene to load the texture in
  41045. * @param rootUrl The root url of the data assets to load
  41046. * @return A color gradind texture
  41047. */
  41048. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41049. var texture = null;
  41050. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41051. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41052. texture.name = parsedTexture.name;
  41053. texture.level = parsedTexture.level;
  41054. }
  41055. return texture;
  41056. };
  41057. /**
  41058. * Serializes the LUT texture to json format.
  41059. */
  41060. ColorGradingTexture.prototype.serialize = function () {
  41061. if (!this.name) {
  41062. return null;
  41063. }
  41064. var serializationObject = {};
  41065. serializationObject.name = this.name;
  41066. serializationObject.level = this.level;
  41067. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41068. return serializationObject;
  41069. };
  41070. /**
  41071. * Empty line regex stored for GC.
  41072. */
  41073. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41074. return ColorGradingTexture;
  41075. }(BABYLON.BaseTexture));
  41076. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41077. })(BABYLON || (BABYLON = {}));
  41078. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41079. var BABYLON;
  41080. (function (BABYLON) {
  41081. /**
  41082. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41083. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41084. * 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;
  41085. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41086. */
  41087. var ColorCurves = /** @class */ (function () {
  41088. function ColorCurves() {
  41089. this._dirty = true;
  41090. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41091. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41092. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41093. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41094. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41095. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41096. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41097. this._globalHue = 30;
  41098. this._globalDensity = 0;
  41099. this._globalSaturation = 0;
  41100. this._globalExposure = 0;
  41101. this._highlightsHue = 30;
  41102. this._highlightsDensity = 0;
  41103. this._highlightsSaturation = 0;
  41104. this._highlightsExposure = 0;
  41105. this._midtonesHue = 30;
  41106. this._midtonesDensity = 0;
  41107. this._midtonesSaturation = 0;
  41108. this._midtonesExposure = 0;
  41109. this._shadowsHue = 30;
  41110. this._shadowsDensity = 0;
  41111. this._shadowsSaturation = 0;
  41112. this._shadowsExposure = 0;
  41113. }
  41114. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41115. /**
  41116. * Gets the global Hue value.
  41117. * 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).
  41118. */
  41119. get: function () {
  41120. return this._globalHue;
  41121. },
  41122. /**
  41123. * Sets the global Hue value.
  41124. * 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).
  41125. */
  41126. set: function (value) {
  41127. this._globalHue = value;
  41128. this._dirty = true;
  41129. },
  41130. enumerable: true,
  41131. configurable: true
  41132. });
  41133. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41134. /**
  41135. * Gets the global Density value.
  41136. * 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.
  41137. * Values less than zero provide a filter of opposite hue.
  41138. */
  41139. get: function () {
  41140. return this._globalDensity;
  41141. },
  41142. /**
  41143. * Sets the global Density value.
  41144. * 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.
  41145. * Values less than zero provide a filter of opposite hue.
  41146. */
  41147. set: function (value) {
  41148. this._globalDensity = value;
  41149. this._dirty = true;
  41150. },
  41151. enumerable: true,
  41152. configurable: true
  41153. });
  41154. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41155. /**
  41156. * Gets the global Saturation value.
  41157. * 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.
  41158. */
  41159. get: function () {
  41160. return this._globalSaturation;
  41161. },
  41162. /**
  41163. * Sets the global Saturation value.
  41164. * 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.
  41165. */
  41166. set: function (value) {
  41167. this._globalSaturation = value;
  41168. this._dirty = true;
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41174. /**
  41175. * Gets the highlights Hue value.
  41176. * 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).
  41177. */
  41178. get: function () {
  41179. return this._highlightsHue;
  41180. },
  41181. /**
  41182. * Sets the highlights Hue value.
  41183. * 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).
  41184. */
  41185. set: function (value) {
  41186. this._highlightsHue = value;
  41187. this._dirty = true;
  41188. },
  41189. enumerable: true,
  41190. configurable: true
  41191. });
  41192. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41193. /**
  41194. * Gets the highlights Density value.
  41195. * 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.
  41196. * Values less than zero provide a filter of opposite hue.
  41197. */
  41198. get: function () {
  41199. return this._highlightsDensity;
  41200. },
  41201. /**
  41202. * Sets the highlights Density value.
  41203. * 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.
  41204. * Values less than zero provide a filter of opposite hue.
  41205. */
  41206. set: function (value) {
  41207. this._highlightsDensity = value;
  41208. this._dirty = true;
  41209. },
  41210. enumerable: true,
  41211. configurable: true
  41212. });
  41213. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41214. /**
  41215. * Gets the highlights Saturation value.
  41216. * 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.
  41217. */
  41218. get: function () {
  41219. return this._highlightsSaturation;
  41220. },
  41221. /**
  41222. * Sets the highlights Saturation value.
  41223. * 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.
  41224. */
  41225. set: function (value) {
  41226. this._highlightsSaturation = value;
  41227. this._dirty = true;
  41228. },
  41229. enumerable: true,
  41230. configurable: true
  41231. });
  41232. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41233. /**
  41234. * Gets the highlights Exposure value.
  41235. * 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.
  41236. */
  41237. get: function () {
  41238. return this._highlightsExposure;
  41239. },
  41240. /**
  41241. * Sets the highlights Exposure value.
  41242. * 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.
  41243. */
  41244. set: function (value) {
  41245. this._highlightsExposure = value;
  41246. this._dirty = true;
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41252. /**
  41253. * Gets the midtones Hue value.
  41254. * 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).
  41255. */
  41256. get: function () {
  41257. return this._midtonesHue;
  41258. },
  41259. /**
  41260. * Sets the midtones Hue value.
  41261. * 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).
  41262. */
  41263. set: function (value) {
  41264. this._midtonesHue = value;
  41265. this._dirty = true;
  41266. },
  41267. enumerable: true,
  41268. configurable: true
  41269. });
  41270. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41271. /**
  41272. * Gets the midtones Density value.
  41273. * 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.
  41274. * Values less than zero provide a filter of opposite hue.
  41275. */
  41276. get: function () {
  41277. return this._midtonesDensity;
  41278. },
  41279. /**
  41280. * Sets the midtones Density value.
  41281. * 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.
  41282. * Values less than zero provide a filter of opposite hue.
  41283. */
  41284. set: function (value) {
  41285. this._midtonesDensity = value;
  41286. this._dirty = true;
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41292. /**
  41293. * Gets the midtones Saturation value.
  41294. * 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.
  41295. */
  41296. get: function () {
  41297. return this._midtonesSaturation;
  41298. },
  41299. /**
  41300. * Sets the midtones Saturation value.
  41301. * 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.
  41302. */
  41303. set: function (value) {
  41304. this._midtonesSaturation = value;
  41305. this._dirty = true;
  41306. },
  41307. enumerable: true,
  41308. configurable: true
  41309. });
  41310. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41311. /**
  41312. * Gets the midtones Exposure value.
  41313. * 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.
  41314. */
  41315. get: function () {
  41316. return this._midtonesExposure;
  41317. },
  41318. /**
  41319. * Sets the midtones Exposure value.
  41320. * 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.
  41321. */
  41322. set: function (value) {
  41323. this._midtonesExposure = value;
  41324. this._dirty = true;
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41330. /**
  41331. * Gets the shadows Hue value.
  41332. * 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).
  41333. */
  41334. get: function () {
  41335. return this._shadowsHue;
  41336. },
  41337. /**
  41338. * Sets the shadows Hue value.
  41339. * 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).
  41340. */
  41341. set: function (value) {
  41342. this._shadowsHue = value;
  41343. this._dirty = true;
  41344. },
  41345. enumerable: true,
  41346. configurable: true
  41347. });
  41348. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41349. /**
  41350. * Gets the shadows Density value.
  41351. * 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.
  41352. * Values less than zero provide a filter of opposite hue.
  41353. */
  41354. get: function () {
  41355. return this._shadowsDensity;
  41356. },
  41357. /**
  41358. * Sets the shadows Density value.
  41359. * 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.
  41360. * Values less than zero provide a filter of opposite hue.
  41361. */
  41362. set: function (value) {
  41363. this._shadowsDensity = value;
  41364. this._dirty = true;
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41370. /**
  41371. * Gets the shadows Saturation value.
  41372. * 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.
  41373. */
  41374. get: function () {
  41375. return this._shadowsSaturation;
  41376. },
  41377. /**
  41378. * Sets the shadows Saturation value.
  41379. * 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.
  41380. */
  41381. set: function (value) {
  41382. this._shadowsSaturation = value;
  41383. this._dirty = true;
  41384. },
  41385. enumerable: true,
  41386. configurable: true
  41387. });
  41388. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41389. /**
  41390. * Gets the shadows Exposure value.
  41391. * 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.
  41392. */
  41393. get: function () {
  41394. return this._shadowsExposure;
  41395. },
  41396. /**
  41397. * Sets the shadows Exposure value.
  41398. * 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.
  41399. */
  41400. set: function (value) {
  41401. this._shadowsExposure = value;
  41402. this._dirty = true;
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. ColorCurves.prototype.getClassName = function () {
  41408. return "ColorCurves";
  41409. };
  41410. /**
  41411. * Binds the color curves to the shader.
  41412. * @param colorCurves The color curve to bind
  41413. * @param effect The effect to bind to
  41414. */
  41415. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41416. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41417. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41418. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41419. if (colorCurves._dirty) {
  41420. colorCurves._dirty = false;
  41421. // Fill in global info.
  41422. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41423. // Compute highlights info.
  41424. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41425. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41426. // Compute midtones info.
  41427. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41428. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41429. // Compute shadows info.
  41430. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41431. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41432. // Compute deltas (neutral is midtones).
  41433. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41434. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41435. }
  41436. if (effect) {
  41437. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41438. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41439. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41440. }
  41441. };
  41442. /**
  41443. * Prepare the list of uniforms associated with the ColorCurves effects.
  41444. * @param uniformsList The list of uniforms used in the effect
  41445. */
  41446. ColorCurves.PrepareUniforms = function (uniformsList) {
  41447. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41448. };
  41449. /**
  41450. * Returns color grading data based on a hue, density, saturation and exposure value.
  41451. * @param filterHue The hue of the color filter.
  41452. * @param filterDensity The density of the color filter.
  41453. * @param saturation The saturation.
  41454. * @param exposure The exposure.
  41455. * @param result The result data container.
  41456. */
  41457. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41458. if (hue == null) {
  41459. return;
  41460. }
  41461. hue = ColorCurves.clamp(hue, 0, 360);
  41462. density = ColorCurves.clamp(density, -100, 100);
  41463. saturation = ColorCurves.clamp(saturation, -100, 100);
  41464. exposure = ColorCurves.clamp(exposure, -100, 100);
  41465. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41466. // so that the maximum filter density is only 50% control. This provides fine control
  41467. // for small values and reasonable range.
  41468. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41469. density *= 0.5;
  41470. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41471. if (density < 0) {
  41472. density *= -1;
  41473. hue = (hue + 180) % 360;
  41474. }
  41475. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41476. result.scaleToRef(2, result);
  41477. result.a = 1 + 0.01 * saturation;
  41478. };
  41479. /**
  41480. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41481. * @param value The input slider value in range [-100,100].
  41482. * @returns Adjusted value.
  41483. */
  41484. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41485. value /= 100;
  41486. var x = Math.abs(value);
  41487. x = Math.pow(x, 2);
  41488. if (value < 0) {
  41489. x *= -1;
  41490. }
  41491. x *= 100;
  41492. return x;
  41493. };
  41494. /**
  41495. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41496. * @param hue The hue (H) input.
  41497. * @param saturation The saturation (S) input.
  41498. * @param brightness The brightness (B) input.
  41499. * @result An RGBA color represented as Vector4.
  41500. */
  41501. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41502. var h = ColorCurves.clamp(hue, 0, 360);
  41503. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41504. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41505. if (s === 0) {
  41506. result.r = v;
  41507. result.g = v;
  41508. result.b = v;
  41509. }
  41510. else {
  41511. // sector 0 to 5
  41512. h /= 60;
  41513. var i = Math.floor(h);
  41514. // fractional part of h
  41515. var f = h - i;
  41516. var p = v * (1 - s);
  41517. var q = v * (1 - s * f);
  41518. var t = v * (1 - s * (1 - f));
  41519. switch (i) {
  41520. case 0:
  41521. result.r = v;
  41522. result.g = t;
  41523. result.b = p;
  41524. break;
  41525. case 1:
  41526. result.r = q;
  41527. result.g = v;
  41528. result.b = p;
  41529. break;
  41530. case 2:
  41531. result.r = p;
  41532. result.g = v;
  41533. result.b = t;
  41534. break;
  41535. case 3:
  41536. result.r = p;
  41537. result.g = q;
  41538. result.b = v;
  41539. break;
  41540. case 4:
  41541. result.r = t;
  41542. result.g = p;
  41543. result.b = v;
  41544. break;
  41545. default: // case 5:
  41546. result.r = v;
  41547. result.g = p;
  41548. result.b = q;
  41549. break;
  41550. }
  41551. }
  41552. result.a = 1;
  41553. };
  41554. /**
  41555. * Returns a value clamped between min and max
  41556. * @param value The value to clamp
  41557. * @param min The minimum of value
  41558. * @param max The maximum of value
  41559. * @returns The clamped value.
  41560. */
  41561. ColorCurves.clamp = function (value, min, max) {
  41562. return Math.min(Math.max(value, min), max);
  41563. };
  41564. /**
  41565. * Clones the current color curve instance.
  41566. * @return The cloned curves
  41567. */
  41568. ColorCurves.prototype.clone = function () {
  41569. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41570. };
  41571. /**
  41572. * Serializes the current color curve instance to a json representation.
  41573. * @return a JSON representation
  41574. */
  41575. ColorCurves.prototype.serialize = function () {
  41576. return BABYLON.SerializationHelper.Serialize(this);
  41577. };
  41578. /**
  41579. * Parses the color curve from a json representation.
  41580. * @param source the JSON source to parse
  41581. * @return The parsed curves
  41582. */
  41583. ColorCurves.Parse = function (source) {
  41584. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41585. };
  41586. __decorate([
  41587. BABYLON.serialize()
  41588. ], ColorCurves.prototype, "_globalHue", void 0);
  41589. __decorate([
  41590. BABYLON.serialize()
  41591. ], ColorCurves.prototype, "_globalDensity", void 0);
  41592. __decorate([
  41593. BABYLON.serialize()
  41594. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41595. __decorate([
  41596. BABYLON.serialize()
  41597. ], ColorCurves.prototype, "_globalExposure", void 0);
  41598. __decorate([
  41599. BABYLON.serialize()
  41600. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41601. __decorate([
  41602. BABYLON.serialize()
  41603. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41604. __decorate([
  41605. BABYLON.serialize()
  41606. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41607. __decorate([
  41608. BABYLON.serialize()
  41609. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41610. __decorate([
  41611. BABYLON.serialize()
  41612. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41613. __decorate([
  41614. BABYLON.serialize()
  41615. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41616. __decorate([
  41617. BABYLON.serialize()
  41618. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41619. __decorate([
  41620. BABYLON.serialize()
  41621. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41622. return ColorCurves;
  41623. }());
  41624. BABYLON.ColorCurves = ColorCurves;
  41625. })(BABYLON || (BABYLON = {}));
  41626. //# sourceMappingURL=babylon.colorCurves.js.map
  41627. //# sourceMappingURL=babylon.behavior.js.map
  41628. var BABYLON;
  41629. (function (BABYLON) {
  41630. /**
  41631. * "Static Class" containing the most commonly used helper while dealing with material for
  41632. * rendering purpose.
  41633. *
  41634. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41635. *
  41636. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41637. */
  41638. var MaterialHelper = /** @class */ (function () {
  41639. function MaterialHelper() {
  41640. }
  41641. /**
  41642. * Bind the current view position to an effect.
  41643. * @param effect The effect to be bound
  41644. * @param scene The scene the eyes position is used from
  41645. */
  41646. MaterialHelper.BindEyePosition = function (effect, scene) {
  41647. if (scene._forcedViewPosition) {
  41648. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41649. return;
  41650. }
  41651. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41652. };
  41653. /**
  41654. * Helps preparing the defines values about the UVs in used in the effect.
  41655. * UVs are shared as much as we can accross chanels in the shaders.
  41656. * @param texture The texture we are preparing the UVs for
  41657. * @param defines The defines to update
  41658. * @param key The chanel key "diffuse", "specular"... used in the shader
  41659. */
  41660. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41661. defines._needUVs = true;
  41662. defines[key] = true;
  41663. if (texture.getTextureMatrix().isIdentity(true)) {
  41664. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41665. if (texture.coordinatesIndex === 0) {
  41666. defines["MAINUV1"] = true;
  41667. }
  41668. else {
  41669. defines["MAINUV2"] = true;
  41670. }
  41671. }
  41672. else {
  41673. defines[key + "DIRECTUV"] = 0;
  41674. }
  41675. };
  41676. /**
  41677. * Binds a texture matrix value to its corrsponding uniform
  41678. * @param texture The texture to bind the matrix for
  41679. * @param uniformBuffer The uniform buffer receivin the data
  41680. * @param key The chanel key "diffuse", "specular"... used in the shader
  41681. */
  41682. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41683. var matrix = texture.getTextureMatrix();
  41684. if (!matrix.isIdentity(true)) {
  41685. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41686. }
  41687. };
  41688. /**
  41689. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41690. * @param mesh defines the current mesh
  41691. * @param scene defines the current scene
  41692. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41693. * @param pointsCloud defines if point cloud rendering has to be turned on
  41694. * @param fogEnabled defines if fog has to be turned on
  41695. * @param alphaTest defines if alpha testing has to be turned on
  41696. * @param defines defines the current list of defines
  41697. */
  41698. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41699. if (defines._areMiscDirty) {
  41700. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41701. defines["POINTSIZE"] = pointsCloud;
  41702. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41703. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41704. defines["ALPHATEST"] = alphaTest;
  41705. }
  41706. };
  41707. /**
  41708. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41709. * @param scene defines the current scene
  41710. * @param engine defines the current engine
  41711. * @param defines specifies the list of active defines
  41712. * @param useInstances defines if instances have to be turned on
  41713. * @param useClipPlane defines if clip plane have to be turned on
  41714. */
  41715. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41716. if (useClipPlane === void 0) { useClipPlane = null; }
  41717. var changed = false;
  41718. if (useClipPlane == null) {
  41719. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41720. }
  41721. if (defines["CLIPPLANE"] !== useClipPlane) {
  41722. defines["CLIPPLANE"] = useClipPlane;
  41723. changed = true;
  41724. }
  41725. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41726. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41727. changed = true;
  41728. }
  41729. if (defines["INSTANCES"] !== useInstances) {
  41730. defines["INSTANCES"] = useInstances;
  41731. changed = true;
  41732. }
  41733. if (changed) {
  41734. defines.markAsUnprocessed();
  41735. }
  41736. };
  41737. /**
  41738. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41739. * @param mesh The mesh containing the geometry data we will draw
  41740. * @param defines The defines to update
  41741. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41742. * @param useBones Precise whether bones should be used or not (override mesh info)
  41743. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41744. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41745. * @returns false if defines are considered not dirty and have not been checked
  41746. */
  41747. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41748. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41749. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41750. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41751. return false;
  41752. }
  41753. defines._normals = defines._needNormals;
  41754. defines._uvs = defines._needUVs;
  41755. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41756. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41757. defines["TANGENT"] = true;
  41758. }
  41759. if (defines._needUVs) {
  41760. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41761. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41762. }
  41763. else {
  41764. defines["UV1"] = false;
  41765. defines["UV2"] = false;
  41766. }
  41767. if (useVertexColor) {
  41768. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41769. defines["VERTEXCOLOR"] = hasVertexColors;
  41770. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41771. }
  41772. if (useBones) {
  41773. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41774. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41775. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41776. }
  41777. else {
  41778. defines["NUM_BONE_INFLUENCERS"] = 0;
  41779. defines["BonesPerMesh"] = 0;
  41780. }
  41781. }
  41782. if (useMorphTargets) {
  41783. var manager = mesh.morphTargetManager;
  41784. if (manager) {
  41785. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41786. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41787. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41788. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41789. }
  41790. else {
  41791. defines["MORPHTARGETS_TANGENT"] = false;
  41792. defines["MORPHTARGETS_NORMAL"] = false;
  41793. defines["MORPHTARGETS"] = false;
  41794. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41795. }
  41796. }
  41797. return true;
  41798. };
  41799. /**
  41800. * Prepares the defines related to the light information passed in parameter
  41801. * @param scene The scene we are intending to draw
  41802. * @param mesh The mesh the effect is compiling for
  41803. * @param defines The defines to update
  41804. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41805. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41806. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41807. * @returns true if normals will be required for the rest of the effect
  41808. */
  41809. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41810. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41811. if (disableLighting === void 0) { disableLighting = false; }
  41812. if (!defines._areLightsDirty) {
  41813. return defines._needNormals;
  41814. }
  41815. var lightIndex = 0;
  41816. var needNormals = false;
  41817. var needRebuild = false;
  41818. var lightmapMode = false;
  41819. var shadowEnabled = false;
  41820. var specularEnabled = false;
  41821. if (scene.lightsEnabled && !disableLighting) {
  41822. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41823. var light = _a[_i];
  41824. needNormals = true;
  41825. if (defines["LIGHT" + lightIndex] === undefined) {
  41826. needRebuild = true;
  41827. }
  41828. defines["LIGHT" + lightIndex] = true;
  41829. defines["SPOTLIGHT" + lightIndex] = false;
  41830. defines["HEMILIGHT" + lightIndex] = false;
  41831. defines["POINTLIGHT" + lightIndex] = false;
  41832. defines["DIRLIGHT" + lightIndex] = false;
  41833. var type;
  41834. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41835. type = "SPOTLIGHT" + lightIndex;
  41836. var spotLight = light;
  41837. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41838. }
  41839. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41840. type = "HEMILIGHT" + lightIndex;
  41841. }
  41842. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41843. type = "POINTLIGHT" + lightIndex;
  41844. }
  41845. else {
  41846. type = "DIRLIGHT" + lightIndex;
  41847. }
  41848. defines[type] = true;
  41849. // Specular
  41850. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41851. specularEnabled = true;
  41852. }
  41853. // Shadows
  41854. defines["SHADOW" + lightIndex] = false;
  41855. defines["SHADOWPCF" + lightIndex] = false;
  41856. defines["SHADOWPCSS" + lightIndex] = false;
  41857. defines["SHADOWPOISSON" + lightIndex] = false;
  41858. defines["SHADOWESM" + lightIndex] = false;
  41859. defines["SHADOWCUBE" + lightIndex] = false;
  41860. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41861. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41862. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41863. var shadowGenerator = light.getShadowGenerator();
  41864. if (shadowGenerator) {
  41865. shadowEnabled = true;
  41866. shadowGenerator.prepareDefines(defines, lightIndex);
  41867. }
  41868. }
  41869. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41870. lightmapMode = true;
  41871. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41872. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41873. }
  41874. else {
  41875. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41876. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41877. }
  41878. lightIndex++;
  41879. if (lightIndex === maxSimultaneousLights)
  41880. break;
  41881. }
  41882. }
  41883. defines["SPECULARTERM"] = specularEnabled;
  41884. defines["SHADOWS"] = shadowEnabled;
  41885. // Resetting all other lights if any
  41886. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41887. if (defines["LIGHT" + index] !== undefined) {
  41888. defines["LIGHT" + index] = false;
  41889. defines["HEMILIGHT" + lightIndex] = false;
  41890. defines["POINTLIGHT" + lightIndex] = false;
  41891. defines["DIRLIGHT" + lightIndex] = false;
  41892. defines["SPOTLIGHT" + lightIndex] = false;
  41893. defines["SHADOW" + lightIndex] = false;
  41894. }
  41895. }
  41896. var caps = scene.getEngine().getCaps();
  41897. if (defines["SHADOWFLOAT"] === undefined) {
  41898. needRebuild = true;
  41899. }
  41900. defines["SHADOWFLOAT"] = shadowEnabled &&
  41901. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41902. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41903. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41904. if (needRebuild) {
  41905. defines.rebuild();
  41906. }
  41907. return needNormals;
  41908. };
  41909. /**
  41910. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41911. * that won t be acctive due to defines being turned off.
  41912. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41913. * @param samplersList The samplers list
  41914. * @param defines The defines helping in the list generation
  41915. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41916. */
  41917. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41918. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41919. var uniformsList;
  41920. var uniformBuffersList = null;
  41921. if (uniformsListOrOptions.uniformsNames) {
  41922. var options = uniformsListOrOptions;
  41923. uniformsList = options.uniformsNames;
  41924. uniformBuffersList = options.uniformBuffersNames;
  41925. samplersList = options.samplers;
  41926. defines = options.defines;
  41927. maxSimultaneousLights = options.maxSimultaneousLights;
  41928. }
  41929. else {
  41930. uniformsList = uniformsListOrOptions;
  41931. if (!samplersList) {
  41932. samplersList = [];
  41933. }
  41934. }
  41935. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41936. if (!defines["LIGHT" + lightIndex]) {
  41937. break;
  41938. }
  41939. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41940. if (uniformBuffersList) {
  41941. uniformBuffersList.push("Light" + lightIndex);
  41942. }
  41943. samplersList.push("shadowSampler" + lightIndex);
  41944. samplersList.push("depthSampler" + lightIndex);
  41945. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41946. samplersList.push("projectionLightSampler" + lightIndex);
  41947. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41948. }
  41949. }
  41950. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41951. uniformsList.push("morphTargetInfluences");
  41952. }
  41953. };
  41954. /**
  41955. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41956. * @param defines The defines to update while falling back
  41957. * @param fallbacks The authorized effect fallbacks
  41958. * @param maxSimultaneousLights The maximum number of lights allowed
  41959. * @param rank the current rank of the Effect
  41960. * @returns The newly affected rank
  41961. */
  41962. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41963. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41964. if (rank === void 0) { rank = 0; }
  41965. var lightFallbackRank = 0;
  41966. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41967. if (!defines["LIGHT" + lightIndex]) {
  41968. break;
  41969. }
  41970. if (lightIndex > 0) {
  41971. lightFallbackRank = rank + lightIndex;
  41972. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41973. }
  41974. if (!defines["SHADOWS"]) {
  41975. if (defines["SHADOW" + lightIndex]) {
  41976. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41977. }
  41978. if (defines["SHADOWPCF" + lightIndex]) {
  41979. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41980. }
  41981. if (defines["SHADOWPCSS" + lightIndex]) {
  41982. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41983. }
  41984. if (defines["SHADOWPOISSON" + lightIndex]) {
  41985. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41986. }
  41987. if (defines["SHADOWESM" + lightIndex]) {
  41988. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41989. }
  41990. }
  41991. }
  41992. return lightFallbackRank++;
  41993. };
  41994. /**
  41995. * Prepares the list of attributes required for morph targets according to the effect defines.
  41996. * @param attribs The current list of supported attribs
  41997. * @param mesh The mesh to prepare the morph targets attributes for
  41998. * @param defines The current Defines of the effect
  41999. */
  42000. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42001. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42002. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42003. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42004. var manager = mesh.morphTargetManager;
  42005. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42006. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42007. for (var index = 0; index < influencers; index++) {
  42008. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42009. if (normal) {
  42010. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42011. }
  42012. if (tangent) {
  42013. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42014. }
  42015. if (attribs.length > maxAttributesCount) {
  42016. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42017. }
  42018. }
  42019. }
  42020. };
  42021. /**
  42022. * Prepares the list of attributes required for bones according to the effect defines.
  42023. * @param attribs The current list of supported attribs
  42024. * @param mesh The mesh to prepare the bones attributes for
  42025. * @param defines The current Defines of the effect
  42026. * @param fallbacks The current efffect fallback strategy
  42027. */
  42028. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42029. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42030. fallbacks.addCPUSkinningFallback(0, mesh);
  42031. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42032. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42033. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42034. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42035. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42036. }
  42037. }
  42038. };
  42039. /**
  42040. * Prepares the list of attributes required for instances according to the effect defines.
  42041. * @param attribs The current list of supported attribs
  42042. * @param defines The current Defines of the effect
  42043. */
  42044. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42045. if (defines["INSTANCES"]) {
  42046. attribs.push("world0");
  42047. attribs.push("world1");
  42048. attribs.push("world2");
  42049. attribs.push("world3");
  42050. }
  42051. };
  42052. /**
  42053. * Binds the light shadow information to the effect for the given mesh.
  42054. * @param light The light containing the generator
  42055. * @param scene The scene the lights belongs to
  42056. * @param mesh The mesh we are binding the information to render
  42057. * @param lightIndex The light index in the effect used to render the mesh
  42058. * @param effect The effect we are binding the data to
  42059. */
  42060. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42061. if (light.shadowEnabled && mesh.receiveShadows) {
  42062. var shadowGenerator = light.getShadowGenerator();
  42063. if (shadowGenerator) {
  42064. shadowGenerator.bindShadowLight(lightIndex, effect);
  42065. }
  42066. }
  42067. };
  42068. /**
  42069. * Binds the light information to the effect.
  42070. * @param light The light containing the generator
  42071. * @param effect The effect we are binding the data to
  42072. * @param lightIndex The light index in the effect used to render
  42073. */
  42074. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42075. light.transferToEffect(effect, lightIndex + "");
  42076. };
  42077. /**
  42078. * Binds the lights information from the scene to the effect for the given mesh.
  42079. * @param scene The scene the lights belongs to
  42080. * @param mesh The mesh we are binding the information to render
  42081. * @param effect The effect we are binding the data to
  42082. * @param defines The generated defines for the effect
  42083. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42084. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42085. */
  42086. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42087. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42088. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42089. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42090. for (var i = 0; i < len; i++) {
  42091. var light = mesh._lightSources[i];
  42092. var iAsString = i.toString();
  42093. var scaledIntensity = light.getScaledIntensity();
  42094. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42095. MaterialHelper.BindLightProperties(light, effect, i);
  42096. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42097. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42098. if (defines["SPECULARTERM"]) {
  42099. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42100. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42101. }
  42102. // Shadows
  42103. if (scene.shadowsEnabled) {
  42104. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42105. }
  42106. light._uniformBuffer.update();
  42107. }
  42108. };
  42109. /**
  42110. * Binds the fog information from the scene to the effect for the given mesh.
  42111. * @param scene The scene the lights belongs to
  42112. * @param mesh The mesh we are binding the information to render
  42113. * @param effect The effect we are binding the data to
  42114. */
  42115. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42116. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42117. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42118. effect.setColor3("vFogColor", scene.fogColor);
  42119. }
  42120. };
  42121. /**
  42122. * Binds the bones information from the mesh to the effect.
  42123. * @param mesh The mesh we are binding the information to render
  42124. * @param effect The effect we are binding the data to
  42125. */
  42126. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42127. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42128. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42129. if (matrices && effect) {
  42130. effect.setMatrices("mBones", matrices);
  42131. }
  42132. }
  42133. };
  42134. /**
  42135. * Binds the morph targets information from the mesh to the effect.
  42136. * @param abstractMesh The mesh we are binding the information to render
  42137. * @param effect The effect we are binding the data to
  42138. */
  42139. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42140. var manager = abstractMesh.morphTargetManager;
  42141. if (!abstractMesh || !manager) {
  42142. return;
  42143. }
  42144. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42145. };
  42146. /**
  42147. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42148. * @param defines The generated defines used in the effect
  42149. * @param effect The effect we are binding the data to
  42150. * @param scene The scene we are willing to render with logarithmic scale for
  42151. */
  42152. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42153. if (defines["LOGARITHMICDEPTH"]) {
  42154. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42155. }
  42156. };
  42157. /**
  42158. * Binds the clip plane information from the scene to the effect.
  42159. * @param scene The scene the clip plane information are extracted from
  42160. * @param effect The effect we are binding the data to
  42161. */
  42162. MaterialHelper.BindClipPlane = function (effect, scene) {
  42163. if (scene.clipPlane) {
  42164. var clipPlane = scene.clipPlane;
  42165. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42166. }
  42167. };
  42168. return MaterialHelper;
  42169. }());
  42170. BABYLON.MaterialHelper = MaterialHelper;
  42171. })(BABYLON || (BABYLON = {}));
  42172. //# sourceMappingURL=babylon.materialHelper.js.map
  42173. var BABYLON;
  42174. (function (BABYLON) {
  42175. var PushMaterial = /** @class */ (function (_super) {
  42176. __extends(PushMaterial, _super);
  42177. function PushMaterial(name, scene) {
  42178. var _this = _super.call(this, name, scene) || this;
  42179. _this._normalMatrix = new BABYLON.Matrix();
  42180. _this.storeEffectOnSubMeshes = true;
  42181. return _this;
  42182. }
  42183. PushMaterial.prototype.getEffect = function () {
  42184. return this._activeEffect;
  42185. };
  42186. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42187. if (!mesh) {
  42188. return false;
  42189. }
  42190. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42191. return true;
  42192. }
  42193. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42194. };
  42195. /**
  42196. * Binds the given world matrix to the active effect
  42197. *
  42198. * @param world the matrix to bind
  42199. */
  42200. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42201. this._activeEffect.setMatrix("world", world);
  42202. };
  42203. /**
  42204. * Binds the given normal matrix to the active effect
  42205. *
  42206. * @param normalMatrix the matrix to bind
  42207. */
  42208. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42209. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42210. };
  42211. PushMaterial.prototype.bind = function (world, mesh) {
  42212. if (!mesh) {
  42213. return;
  42214. }
  42215. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42216. };
  42217. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42218. if (effect === void 0) { effect = null; }
  42219. _super.prototype._afterBind.call(this, mesh);
  42220. this.getScene()._cachedEffect = effect;
  42221. };
  42222. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42223. if (visibility === void 0) { visibility = 1; }
  42224. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42225. };
  42226. return PushMaterial;
  42227. }(BABYLON.Material));
  42228. BABYLON.PushMaterial = PushMaterial;
  42229. })(BABYLON || (BABYLON = {}));
  42230. //# sourceMappingURL=babylon.pushMaterial.js.map
  42231. var BABYLON;
  42232. (function (BABYLON) {
  42233. /** @ignore */
  42234. var StandardMaterialDefines = /** @class */ (function (_super) {
  42235. __extends(StandardMaterialDefines, _super);
  42236. function StandardMaterialDefines() {
  42237. var _this = _super.call(this) || this;
  42238. _this.MAINUV1 = false;
  42239. _this.MAINUV2 = false;
  42240. _this.DIFFUSE = false;
  42241. _this.DIFFUSEDIRECTUV = 0;
  42242. _this.AMBIENT = false;
  42243. _this.AMBIENTDIRECTUV = 0;
  42244. _this.OPACITY = false;
  42245. _this.OPACITYDIRECTUV = 0;
  42246. _this.OPACITYRGB = false;
  42247. _this.REFLECTION = false;
  42248. _this.EMISSIVE = false;
  42249. _this.EMISSIVEDIRECTUV = 0;
  42250. _this.SPECULAR = false;
  42251. _this.SPECULARDIRECTUV = 0;
  42252. _this.BUMP = false;
  42253. _this.BUMPDIRECTUV = 0;
  42254. _this.PARALLAX = false;
  42255. _this.PARALLAXOCCLUSION = false;
  42256. _this.SPECULAROVERALPHA = false;
  42257. _this.CLIPPLANE = false;
  42258. _this.ALPHATEST = false;
  42259. _this.DEPTHPREPASS = false;
  42260. _this.ALPHAFROMDIFFUSE = false;
  42261. _this.POINTSIZE = false;
  42262. _this.FOG = false;
  42263. _this.SPECULARTERM = false;
  42264. _this.DIFFUSEFRESNEL = false;
  42265. _this.OPACITYFRESNEL = false;
  42266. _this.REFLECTIONFRESNEL = false;
  42267. _this.REFRACTIONFRESNEL = false;
  42268. _this.EMISSIVEFRESNEL = false;
  42269. _this.FRESNEL = false;
  42270. _this.NORMAL = false;
  42271. _this.UV1 = false;
  42272. _this.UV2 = false;
  42273. _this.VERTEXCOLOR = false;
  42274. _this.VERTEXALPHA = false;
  42275. _this.NUM_BONE_INFLUENCERS = 0;
  42276. _this.BonesPerMesh = 0;
  42277. _this.INSTANCES = false;
  42278. _this.GLOSSINESS = false;
  42279. _this.ROUGHNESS = false;
  42280. _this.EMISSIVEASILLUMINATION = false;
  42281. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42282. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42283. _this.LIGHTMAP = false;
  42284. _this.LIGHTMAPDIRECTUV = 0;
  42285. _this.OBJECTSPACE_NORMALMAP = false;
  42286. _this.USELIGHTMAPASSHADOWMAP = false;
  42287. _this.REFLECTIONMAP_3D = false;
  42288. _this.REFLECTIONMAP_SPHERICAL = false;
  42289. _this.REFLECTIONMAP_PLANAR = false;
  42290. _this.REFLECTIONMAP_CUBIC = false;
  42291. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42292. _this.REFLECTIONMAP_PROJECTION = false;
  42293. _this.REFLECTIONMAP_SKYBOX = false;
  42294. _this.REFLECTIONMAP_EXPLICIT = false;
  42295. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42296. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42297. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42298. _this.INVERTCUBICMAP = false;
  42299. _this.LOGARITHMICDEPTH = false;
  42300. _this.REFRACTION = false;
  42301. _this.REFRACTIONMAP_3D = false;
  42302. _this.REFLECTIONOVERALPHA = false;
  42303. _this.TWOSIDEDLIGHTING = false;
  42304. _this.SHADOWFLOAT = false;
  42305. _this.MORPHTARGETS = false;
  42306. _this.MORPHTARGETS_NORMAL = false;
  42307. _this.MORPHTARGETS_TANGENT = false;
  42308. _this.NUM_MORPH_INFLUENCERS = 0;
  42309. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42310. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42311. _this.IMAGEPROCESSING = false;
  42312. _this.VIGNETTE = false;
  42313. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42314. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42315. _this.TONEMAPPING = false;
  42316. _this.CONTRAST = false;
  42317. _this.COLORCURVES = false;
  42318. _this.COLORGRADING = false;
  42319. _this.COLORGRADING3D = false;
  42320. _this.SAMPLER3DGREENDEPTH = false;
  42321. _this.SAMPLER3DBGRMAP = false;
  42322. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42323. /**
  42324. * If the reflection texture on this material is in linear color space
  42325. * @ignore
  42326. */
  42327. _this.IS_REFLECTION_LINEAR = false;
  42328. /**
  42329. * If the refraction texture on this material is in linear color space
  42330. * @ignore
  42331. */
  42332. _this.IS_REFRACTION_LINEAR = false;
  42333. _this.EXPOSURE = false;
  42334. _this.rebuild();
  42335. return _this;
  42336. }
  42337. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42338. var modes = [
  42339. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42340. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42341. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42342. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42343. ];
  42344. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42345. var mode = modes_1[_i];
  42346. this[mode] = (mode === modeToEnable);
  42347. }
  42348. };
  42349. return StandardMaterialDefines;
  42350. }(BABYLON.MaterialDefines));
  42351. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42352. var StandardMaterial = /** @class */ (function (_super) {
  42353. __extends(StandardMaterial, _super);
  42354. function StandardMaterial(name, scene) {
  42355. var _this = _super.call(this, name, scene) || this;
  42356. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42357. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42358. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42359. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42360. _this.specularPower = 64;
  42361. _this._useAlphaFromDiffuseTexture = false;
  42362. _this._useEmissiveAsIllumination = false;
  42363. _this._linkEmissiveWithDiffuse = false;
  42364. _this._useSpecularOverAlpha = false;
  42365. _this._useReflectionOverAlpha = false;
  42366. _this._disableLighting = false;
  42367. _this._useObjectSpaceNormalMap = false;
  42368. _this._useParallax = false;
  42369. _this._useParallaxOcclusion = false;
  42370. _this.parallaxScaleBias = 0.05;
  42371. _this._roughness = 0;
  42372. _this.indexOfRefraction = 0.98;
  42373. _this.invertRefractionY = true;
  42374. /**
  42375. * Defines the alpha limits in alpha test mode
  42376. */
  42377. _this.alphaCutOff = 0.4;
  42378. _this._useLightmapAsShadowmap = false;
  42379. _this._useReflectionFresnelFromSpecular = false;
  42380. _this._useGlossinessFromSpecularMapAlpha = false;
  42381. _this._maxSimultaneousLights = 4;
  42382. /**
  42383. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42384. */
  42385. _this._invertNormalMapX = false;
  42386. /**
  42387. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42388. */
  42389. _this._invertNormalMapY = false;
  42390. /**
  42391. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42392. */
  42393. _this._twoSidedLighting = false;
  42394. _this._renderTargets = new BABYLON.SmartArray(16);
  42395. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42396. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42397. // Setup the default processing configuration to the scene.
  42398. _this._attachImageProcessingConfiguration(null);
  42399. _this.getRenderTargetTextures = function () {
  42400. _this._renderTargets.reset();
  42401. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42402. _this._renderTargets.push(_this._reflectionTexture);
  42403. }
  42404. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42405. _this._renderTargets.push(_this._refractionTexture);
  42406. }
  42407. return _this._renderTargets;
  42408. };
  42409. return _this;
  42410. }
  42411. ;
  42412. ;
  42413. ;
  42414. ;
  42415. ;
  42416. ;
  42417. ;
  42418. ;
  42419. ;
  42420. ;
  42421. ;
  42422. ;
  42423. ;
  42424. ;
  42425. ;
  42426. ;
  42427. ;
  42428. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42429. /**
  42430. * Gets the image processing configuration used either in this material.
  42431. */
  42432. get: function () {
  42433. return this._imageProcessingConfiguration;
  42434. },
  42435. /**
  42436. * Sets the Default image processing configuration used either in the this material.
  42437. *
  42438. * If sets to null, the scene one is in use.
  42439. */
  42440. set: function (value) {
  42441. this._attachImageProcessingConfiguration(value);
  42442. // Ensure the effect will be rebuilt.
  42443. this._markAllSubMeshesAsTexturesDirty();
  42444. },
  42445. enumerable: true,
  42446. configurable: true
  42447. });
  42448. /**
  42449. * Attaches a new image processing configuration to the Standard Material.
  42450. * @param configuration
  42451. */
  42452. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42453. var _this = this;
  42454. if (configuration === this._imageProcessingConfiguration) {
  42455. return;
  42456. }
  42457. // Detaches observer.
  42458. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42459. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42460. }
  42461. // Pick the scene configuration if needed.
  42462. if (!configuration) {
  42463. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42464. }
  42465. else {
  42466. this._imageProcessingConfiguration = configuration;
  42467. }
  42468. // Attaches observer.
  42469. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42470. _this._markAllSubMeshesAsImageProcessingDirty();
  42471. });
  42472. };
  42473. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42474. /**
  42475. * Gets wether the color curves effect is enabled.
  42476. */
  42477. get: function () {
  42478. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42479. },
  42480. /**
  42481. * Sets wether the color curves effect is enabled.
  42482. */
  42483. set: function (value) {
  42484. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42485. },
  42486. enumerable: true,
  42487. configurable: true
  42488. });
  42489. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42490. /**
  42491. * Gets wether the color grading effect is enabled.
  42492. */
  42493. get: function () {
  42494. return this.imageProcessingConfiguration.colorGradingEnabled;
  42495. },
  42496. /**
  42497. * Gets wether the color grading effect is enabled.
  42498. */
  42499. set: function (value) {
  42500. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42501. },
  42502. enumerable: true,
  42503. configurable: true
  42504. });
  42505. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42506. /**
  42507. * Gets wether tonemapping is enabled or not.
  42508. */
  42509. get: function () {
  42510. return this._imageProcessingConfiguration.toneMappingEnabled;
  42511. },
  42512. /**
  42513. * Sets wether tonemapping is enabled or not
  42514. */
  42515. set: function (value) {
  42516. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. ;
  42522. ;
  42523. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42524. /**
  42525. * The camera exposure used on this material.
  42526. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42527. * This corresponds to a photographic exposure.
  42528. */
  42529. get: function () {
  42530. return this._imageProcessingConfiguration.exposure;
  42531. },
  42532. /**
  42533. * The camera exposure used on this material.
  42534. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42535. * This corresponds to a photographic exposure.
  42536. */
  42537. set: function (value) {
  42538. this._imageProcessingConfiguration.exposure = value;
  42539. },
  42540. enumerable: true,
  42541. configurable: true
  42542. });
  42543. ;
  42544. ;
  42545. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42546. /**
  42547. * Gets The camera contrast used on this material.
  42548. */
  42549. get: function () {
  42550. return this._imageProcessingConfiguration.contrast;
  42551. },
  42552. /**
  42553. * Sets The camera contrast used on this material.
  42554. */
  42555. set: function (value) {
  42556. this._imageProcessingConfiguration.contrast = value;
  42557. },
  42558. enumerable: true,
  42559. configurable: true
  42560. });
  42561. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42562. /**
  42563. * Gets the Color Grading 2D Lookup Texture.
  42564. */
  42565. get: function () {
  42566. return this._imageProcessingConfiguration.colorGradingTexture;
  42567. },
  42568. /**
  42569. * Sets the Color Grading 2D Lookup Texture.
  42570. */
  42571. set: function (value) {
  42572. this._imageProcessingConfiguration.colorGradingTexture = value;
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42578. /**
  42579. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42580. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42581. * 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;
  42582. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42583. */
  42584. get: function () {
  42585. return this._imageProcessingConfiguration.colorCurves;
  42586. },
  42587. /**
  42588. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42589. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42590. * 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;
  42591. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42592. */
  42593. set: function (value) {
  42594. this._imageProcessingConfiguration.colorCurves = value;
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. StandardMaterial.prototype.getClassName = function () {
  42600. return "StandardMaterial";
  42601. };
  42602. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42603. get: function () {
  42604. return this._useLogarithmicDepth;
  42605. },
  42606. set: function (value) {
  42607. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42608. this._markAllSubMeshesAsMiscDirty();
  42609. },
  42610. enumerable: true,
  42611. configurable: true
  42612. });
  42613. StandardMaterial.prototype.needAlphaBlending = function () {
  42614. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42615. };
  42616. StandardMaterial.prototype.needAlphaTesting = function () {
  42617. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42618. };
  42619. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42620. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42621. };
  42622. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42623. return this._diffuseTexture;
  42624. };
  42625. /**
  42626. * Child classes can use it to update shaders
  42627. */
  42628. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42629. if (useInstances === void 0) { useInstances = false; }
  42630. if (subMesh.effect && this.isFrozen) {
  42631. if (this._wasPreviouslyReady && subMesh.effect) {
  42632. return true;
  42633. }
  42634. }
  42635. if (!subMesh._materialDefines) {
  42636. subMesh._materialDefines = new StandardMaterialDefines();
  42637. }
  42638. var scene = this.getScene();
  42639. var defines = subMesh._materialDefines;
  42640. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42641. if (defines._renderId === scene.getRenderId()) {
  42642. return true;
  42643. }
  42644. }
  42645. var engine = scene.getEngine();
  42646. // Lights
  42647. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42648. // Textures
  42649. if (defines._areTexturesDirty) {
  42650. defines._needUVs = false;
  42651. defines.MAINUV1 = false;
  42652. defines.MAINUV2 = false;
  42653. if (scene.texturesEnabled) {
  42654. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42655. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42656. return false;
  42657. }
  42658. else {
  42659. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42660. }
  42661. }
  42662. else {
  42663. defines.DIFFUSE = false;
  42664. }
  42665. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42666. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42667. return false;
  42668. }
  42669. else {
  42670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42671. }
  42672. }
  42673. else {
  42674. defines.AMBIENT = false;
  42675. }
  42676. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42677. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42678. return false;
  42679. }
  42680. else {
  42681. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42682. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42683. }
  42684. }
  42685. else {
  42686. defines.OPACITY = false;
  42687. }
  42688. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42689. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42690. return false;
  42691. }
  42692. else {
  42693. defines._needNormals = true;
  42694. defines.REFLECTION = true;
  42695. defines.ROUGHNESS = (this._roughness > 0);
  42696. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42697. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42698. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42699. switch (this._reflectionTexture.coordinatesMode) {
  42700. case BABYLON.Texture.CUBIC_MODE:
  42701. case BABYLON.Texture.INVCUBIC_MODE:
  42702. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42703. break;
  42704. case BABYLON.Texture.EXPLICIT_MODE:
  42705. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42706. break;
  42707. case BABYLON.Texture.PLANAR_MODE:
  42708. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42709. break;
  42710. case BABYLON.Texture.PROJECTION_MODE:
  42711. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42712. break;
  42713. case BABYLON.Texture.SKYBOX_MODE:
  42714. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42715. break;
  42716. case BABYLON.Texture.SPHERICAL_MODE:
  42717. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42718. break;
  42719. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42720. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42721. break;
  42722. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42723. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42724. break;
  42725. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42726. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42727. break;
  42728. }
  42729. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42730. }
  42731. }
  42732. else {
  42733. defines.REFLECTION = false;
  42734. }
  42735. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42736. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42737. return false;
  42738. }
  42739. else {
  42740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42741. }
  42742. }
  42743. else {
  42744. defines.EMISSIVE = false;
  42745. }
  42746. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42747. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42748. return false;
  42749. }
  42750. else {
  42751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42752. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42753. }
  42754. }
  42755. else {
  42756. defines.LIGHTMAP = false;
  42757. }
  42758. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42759. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42760. return false;
  42761. }
  42762. else {
  42763. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42764. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42765. }
  42766. }
  42767. else {
  42768. defines.SPECULAR = false;
  42769. }
  42770. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42771. // Bump texure can not be not blocking.
  42772. if (!this._bumpTexture.isReady()) {
  42773. return false;
  42774. }
  42775. else {
  42776. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42777. defines.PARALLAX = this._useParallax;
  42778. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42779. }
  42780. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42781. }
  42782. else {
  42783. defines.BUMP = false;
  42784. }
  42785. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42786. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42787. return false;
  42788. }
  42789. else {
  42790. defines._needUVs = true;
  42791. defines.REFRACTION = true;
  42792. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42793. }
  42794. }
  42795. else {
  42796. defines.REFRACTION = false;
  42797. }
  42798. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42799. }
  42800. else {
  42801. defines.DIFFUSE = false;
  42802. defines.AMBIENT = false;
  42803. defines.OPACITY = false;
  42804. defines.REFLECTION = false;
  42805. defines.EMISSIVE = false;
  42806. defines.LIGHTMAP = false;
  42807. defines.BUMP = false;
  42808. defines.REFRACTION = false;
  42809. }
  42810. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42811. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42812. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42813. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42814. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42815. }
  42816. if (defines._areImageProcessingDirty) {
  42817. if (!this._imageProcessingConfiguration.isReady()) {
  42818. return false;
  42819. }
  42820. this._imageProcessingConfiguration.prepareDefines(defines);
  42821. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42822. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42823. }
  42824. if (defines._areFresnelDirty) {
  42825. if (StandardMaterial.FresnelEnabled) {
  42826. // Fresnel
  42827. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42828. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42829. this._reflectionFresnelParameters) {
  42830. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42831. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42832. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42833. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42834. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42835. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42836. defines._needNormals = true;
  42837. defines.FRESNEL = true;
  42838. }
  42839. }
  42840. else {
  42841. defines.FRESNEL = false;
  42842. }
  42843. }
  42844. // Misc.
  42845. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42846. // Attribs
  42847. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42848. // Values that need to be evaluated on every frame
  42849. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42850. // Get correct effect
  42851. if (defines.isDirty) {
  42852. defines.markAsProcessed();
  42853. scene.resetCachedMaterial();
  42854. // Fallbacks
  42855. var fallbacks = new BABYLON.EffectFallbacks();
  42856. if (defines.REFLECTION) {
  42857. fallbacks.addFallback(0, "REFLECTION");
  42858. }
  42859. if (defines.SPECULAR) {
  42860. fallbacks.addFallback(0, "SPECULAR");
  42861. }
  42862. if (defines.BUMP) {
  42863. fallbacks.addFallback(0, "BUMP");
  42864. }
  42865. if (defines.PARALLAX) {
  42866. fallbacks.addFallback(1, "PARALLAX");
  42867. }
  42868. if (defines.PARALLAXOCCLUSION) {
  42869. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42870. }
  42871. if (defines.SPECULAROVERALPHA) {
  42872. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42873. }
  42874. if (defines.FOG) {
  42875. fallbacks.addFallback(1, "FOG");
  42876. }
  42877. if (defines.POINTSIZE) {
  42878. fallbacks.addFallback(0, "POINTSIZE");
  42879. }
  42880. if (defines.LOGARITHMICDEPTH) {
  42881. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42882. }
  42883. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42884. if (defines.SPECULARTERM) {
  42885. fallbacks.addFallback(0, "SPECULARTERM");
  42886. }
  42887. if (defines.DIFFUSEFRESNEL) {
  42888. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42889. }
  42890. if (defines.OPACITYFRESNEL) {
  42891. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42892. }
  42893. if (defines.REFLECTIONFRESNEL) {
  42894. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42895. }
  42896. if (defines.EMISSIVEFRESNEL) {
  42897. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42898. }
  42899. if (defines.FRESNEL) {
  42900. fallbacks.addFallback(4, "FRESNEL");
  42901. }
  42902. //Attributes
  42903. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42904. if (defines.NORMAL) {
  42905. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42906. }
  42907. if (defines.UV1) {
  42908. attribs.push(BABYLON.VertexBuffer.UVKind);
  42909. }
  42910. if (defines.UV2) {
  42911. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42912. }
  42913. if (defines.VERTEXCOLOR) {
  42914. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42915. }
  42916. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42917. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42918. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42919. var shaderName = "default";
  42920. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42921. "vFogInfos", "vFogColor", "pointSize",
  42922. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42923. "mBones",
  42924. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42925. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42926. "vReflectionPosition", "vReflectionSize",
  42927. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42928. ];
  42929. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42930. var uniformBuffers = ["Material", "Scene"];
  42931. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42932. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42933. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42934. uniformsNames: uniforms,
  42935. uniformBuffersNames: uniformBuffers,
  42936. samplers: samplers,
  42937. defines: defines,
  42938. maxSimultaneousLights: this._maxSimultaneousLights
  42939. });
  42940. if (this.customShaderNameResolve) {
  42941. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42942. }
  42943. var join = defines.toString();
  42944. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42945. attributes: attribs,
  42946. uniformsNames: uniforms,
  42947. uniformBuffersNames: uniformBuffers,
  42948. samplers: samplers,
  42949. defines: join,
  42950. fallbacks: fallbacks,
  42951. onCompiled: this.onCompiled,
  42952. onError: this.onError,
  42953. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42954. }, engine), defines);
  42955. this.buildUniformLayout();
  42956. }
  42957. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42958. return false;
  42959. }
  42960. defines._renderId = scene.getRenderId();
  42961. this._wasPreviouslyReady = true;
  42962. return true;
  42963. };
  42964. StandardMaterial.prototype.buildUniformLayout = function () {
  42965. // Order is important !
  42966. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42967. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42968. this._uniformBuffer.addUniform("opacityParts", 4);
  42969. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42970. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42971. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42972. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42973. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42974. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42975. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42976. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42977. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42978. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42979. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42980. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42981. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42982. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42983. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42984. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42985. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42986. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42987. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42988. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42989. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42990. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42991. this._uniformBuffer.addUniform("specularMatrix", 16);
  42992. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42993. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42994. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42995. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42996. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42997. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42998. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42999. this._uniformBuffer.addUniform("pointSize", 1);
  43000. this._uniformBuffer.create();
  43001. };
  43002. StandardMaterial.prototype.unbind = function () {
  43003. if (this._activeEffect) {
  43004. var needFlag = false;
  43005. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43006. this._activeEffect.setTexture("reflection2DSampler", null);
  43007. needFlag = true;
  43008. }
  43009. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43010. this._activeEffect.setTexture("refraction2DSampler", null);
  43011. needFlag = true;
  43012. }
  43013. if (needFlag) {
  43014. this._markAllSubMeshesAsTexturesDirty();
  43015. }
  43016. }
  43017. _super.prototype.unbind.call(this);
  43018. };
  43019. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43020. var scene = this.getScene();
  43021. var defines = subMesh._materialDefines;
  43022. if (!defines) {
  43023. return;
  43024. }
  43025. var effect = subMesh.effect;
  43026. if (!effect) {
  43027. return;
  43028. }
  43029. this._activeEffect = effect;
  43030. // Matrices
  43031. this.bindOnlyWorldMatrix(world);
  43032. // Normal Matrix
  43033. if (defines.OBJECTSPACE_NORMALMAP) {
  43034. world.toNormalMatrix(this._normalMatrix);
  43035. this.bindOnlyNormalMatrix(this._normalMatrix);
  43036. }
  43037. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43038. // Bones
  43039. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43040. if (mustRebind) {
  43041. this._uniformBuffer.bindToEffect(effect, "Material");
  43042. this.bindViewProjection(effect);
  43043. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43044. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43045. // Fresnel
  43046. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43047. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43048. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43049. }
  43050. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43051. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43052. }
  43053. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43054. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43055. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43056. }
  43057. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43058. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43059. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43060. }
  43061. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43062. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43063. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43064. }
  43065. }
  43066. // Textures
  43067. if (scene.texturesEnabled) {
  43068. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43069. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43070. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43071. if (this._diffuseTexture.hasAlpha) {
  43072. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43073. }
  43074. }
  43075. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43076. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43077. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43078. }
  43079. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43080. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43081. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43082. }
  43083. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43084. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43085. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43086. if (this._reflectionTexture.boundingBoxSize) {
  43087. var cubeTexture = this._reflectionTexture;
  43088. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43089. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43090. }
  43091. }
  43092. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43093. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43094. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43095. }
  43096. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43097. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43098. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43099. }
  43100. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43101. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43102. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43103. }
  43104. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43105. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43106. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43107. if (scene._mirroredCameraPosition) {
  43108. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43109. }
  43110. else {
  43111. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43112. }
  43113. }
  43114. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43115. var depth = 1.0;
  43116. if (!this._refractionTexture.isCube) {
  43117. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43118. if (this._refractionTexture.depth) {
  43119. depth = this._refractionTexture.depth;
  43120. }
  43121. }
  43122. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43123. }
  43124. }
  43125. // Point size
  43126. if (this.pointsCloud) {
  43127. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43128. }
  43129. if (defines.SPECULARTERM) {
  43130. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43131. }
  43132. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43133. // Diffuse
  43134. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43135. }
  43136. // Textures
  43137. if (scene.texturesEnabled) {
  43138. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43139. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43140. }
  43141. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43142. effect.setTexture("ambientSampler", this._ambientTexture);
  43143. }
  43144. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43145. effect.setTexture("opacitySampler", this._opacityTexture);
  43146. }
  43147. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43148. if (this._reflectionTexture.isCube) {
  43149. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43150. }
  43151. else {
  43152. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43153. }
  43154. }
  43155. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43156. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43157. }
  43158. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43159. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43160. }
  43161. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43162. effect.setTexture("specularSampler", this._specularTexture);
  43163. }
  43164. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43165. effect.setTexture("bumpSampler", this._bumpTexture);
  43166. }
  43167. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43168. var depth = 1.0;
  43169. if (this._refractionTexture.isCube) {
  43170. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43171. }
  43172. else {
  43173. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43174. }
  43175. }
  43176. }
  43177. // Clip plane
  43178. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43179. // Colors
  43180. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43181. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43182. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43183. }
  43184. if (mustRebind || !this.isFrozen) {
  43185. // Lights
  43186. if (scene.lightsEnabled && !this._disableLighting) {
  43187. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43188. }
  43189. // View
  43190. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43191. this.bindView(effect);
  43192. }
  43193. // Fog
  43194. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43195. // Morph targets
  43196. if (defines.NUM_MORPH_INFLUENCERS) {
  43197. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43198. }
  43199. // Log. depth
  43200. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43201. // image processing
  43202. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43203. this._imageProcessingConfiguration.bind(this._activeEffect);
  43204. }
  43205. }
  43206. this._uniformBuffer.update();
  43207. this._afterBind(mesh, this._activeEffect);
  43208. };
  43209. StandardMaterial.prototype.getAnimatables = function () {
  43210. var results = [];
  43211. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43212. results.push(this._diffuseTexture);
  43213. }
  43214. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43215. results.push(this._ambientTexture);
  43216. }
  43217. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43218. results.push(this._opacityTexture);
  43219. }
  43220. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43221. results.push(this._reflectionTexture);
  43222. }
  43223. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43224. results.push(this._emissiveTexture);
  43225. }
  43226. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43227. results.push(this._specularTexture);
  43228. }
  43229. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43230. results.push(this._bumpTexture);
  43231. }
  43232. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43233. results.push(this._lightmapTexture);
  43234. }
  43235. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43236. results.push(this._refractionTexture);
  43237. }
  43238. return results;
  43239. };
  43240. StandardMaterial.prototype.getActiveTextures = function () {
  43241. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43242. if (this._diffuseTexture) {
  43243. activeTextures.push(this._diffuseTexture);
  43244. }
  43245. if (this._ambientTexture) {
  43246. activeTextures.push(this._ambientTexture);
  43247. }
  43248. if (this._opacityTexture) {
  43249. activeTextures.push(this._opacityTexture);
  43250. }
  43251. if (this._reflectionTexture) {
  43252. activeTextures.push(this._reflectionTexture);
  43253. }
  43254. if (this._emissiveTexture) {
  43255. activeTextures.push(this._emissiveTexture);
  43256. }
  43257. if (this._specularTexture) {
  43258. activeTextures.push(this._specularTexture);
  43259. }
  43260. if (this._bumpTexture) {
  43261. activeTextures.push(this._bumpTexture);
  43262. }
  43263. if (this._lightmapTexture) {
  43264. activeTextures.push(this._lightmapTexture);
  43265. }
  43266. if (this._refractionTexture) {
  43267. activeTextures.push(this._refractionTexture);
  43268. }
  43269. return activeTextures;
  43270. };
  43271. StandardMaterial.prototype.hasTexture = function (texture) {
  43272. if (_super.prototype.hasTexture.call(this, texture)) {
  43273. return true;
  43274. }
  43275. if (this._diffuseTexture === texture) {
  43276. return true;
  43277. }
  43278. if (this._ambientTexture === texture) {
  43279. return true;
  43280. }
  43281. if (this._opacityTexture === texture) {
  43282. return true;
  43283. }
  43284. if (this._reflectionTexture === texture) {
  43285. return true;
  43286. }
  43287. if (this._emissiveTexture === texture) {
  43288. return true;
  43289. }
  43290. if (this._specularTexture === texture) {
  43291. return true;
  43292. }
  43293. if (this._bumpTexture === texture) {
  43294. return true;
  43295. }
  43296. if (this._lightmapTexture === texture) {
  43297. return true;
  43298. }
  43299. if (this._refractionTexture === texture) {
  43300. return true;
  43301. }
  43302. return false;
  43303. };
  43304. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43305. if (forceDisposeTextures) {
  43306. if (this._diffuseTexture) {
  43307. this._diffuseTexture.dispose();
  43308. }
  43309. if (this._ambientTexture) {
  43310. this._ambientTexture.dispose();
  43311. }
  43312. if (this._opacityTexture) {
  43313. this._opacityTexture.dispose();
  43314. }
  43315. if (this._reflectionTexture) {
  43316. this._reflectionTexture.dispose();
  43317. }
  43318. if (this._emissiveTexture) {
  43319. this._emissiveTexture.dispose();
  43320. }
  43321. if (this._specularTexture) {
  43322. this._specularTexture.dispose();
  43323. }
  43324. if (this._bumpTexture) {
  43325. this._bumpTexture.dispose();
  43326. }
  43327. if (this._lightmapTexture) {
  43328. this._lightmapTexture.dispose();
  43329. }
  43330. if (this._refractionTexture) {
  43331. this._refractionTexture.dispose();
  43332. }
  43333. }
  43334. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43335. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43336. }
  43337. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43338. };
  43339. StandardMaterial.prototype.clone = function (name) {
  43340. var _this = this;
  43341. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43342. result.name = name;
  43343. result.id = name;
  43344. return result;
  43345. };
  43346. StandardMaterial.prototype.serialize = function () {
  43347. return BABYLON.SerializationHelper.Serialize(this);
  43348. };
  43349. // Statics
  43350. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43351. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43352. };
  43353. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43354. get: function () {
  43355. return StandardMaterial._DiffuseTextureEnabled;
  43356. },
  43357. set: function (value) {
  43358. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43359. return;
  43360. }
  43361. StandardMaterial._DiffuseTextureEnabled = value;
  43362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43363. },
  43364. enumerable: true,
  43365. configurable: true
  43366. });
  43367. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43368. get: function () {
  43369. return StandardMaterial._AmbientTextureEnabled;
  43370. },
  43371. set: function (value) {
  43372. if (StandardMaterial._AmbientTextureEnabled === value) {
  43373. return;
  43374. }
  43375. StandardMaterial._AmbientTextureEnabled = value;
  43376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43377. },
  43378. enumerable: true,
  43379. configurable: true
  43380. });
  43381. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43382. get: function () {
  43383. return StandardMaterial._OpacityTextureEnabled;
  43384. },
  43385. set: function (value) {
  43386. if (StandardMaterial._OpacityTextureEnabled === value) {
  43387. return;
  43388. }
  43389. StandardMaterial._OpacityTextureEnabled = value;
  43390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43391. },
  43392. enumerable: true,
  43393. configurable: true
  43394. });
  43395. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43396. get: function () {
  43397. return StandardMaterial._ReflectionTextureEnabled;
  43398. },
  43399. set: function (value) {
  43400. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43401. return;
  43402. }
  43403. StandardMaterial._ReflectionTextureEnabled = value;
  43404. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43405. },
  43406. enumerable: true,
  43407. configurable: true
  43408. });
  43409. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43410. get: function () {
  43411. return StandardMaterial._EmissiveTextureEnabled;
  43412. },
  43413. set: function (value) {
  43414. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43415. return;
  43416. }
  43417. StandardMaterial._EmissiveTextureEnabled = value;
  43418. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43419. },
  43420. enumerable: true,
  43421. configurable: true
  43422. });
  43423. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43424. get: function () {
  43425. return StandardMaterial._SpecularTextureEnabled;
  43426. },
  43427. set: function (value) {
  43428. if (StandardMaterial._SpecularTextureEnabled === value) {
  43429. return;
  43430. }
  43431. StandardMaterial._SpecularTextureEnabled = value;
  43432. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43433. },
  43434. enumerable: true,
  43435. configurable: true
  43436. });
  43437. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43438. get: function () {
  43439. return StandardMaterial._BumpTextureEnabled;
  43440. },
  43441. set: function (value) {
  43442. if (StandardMaterial._BumpTextureEnabled === value) {
  43443. return;
  43444. }
  43445. StandardMaterial._BumpTextureEnabled = value;
  43446. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43447. },
  43448. enumerable: true,
  43449. configurable: true
  43450. });
  43451. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43452. get: function () {
  43453. return StandardMaterial._LightmapTextureEnabled;
  43454. },
  43455. set: function (value) {
  43456. if (StandardMaterial._LightmapTextureEnabled === value) {
  43457. return;
  43458. }
  43459. StandardMaterial._LightmapTextureEnabled = value;
  43460. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43461. },
  43462. enumerable: true,
  43463. configurable: true
  43464. });
  43465. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43466. get: function () {
  43467. return StandardMaterial._RefractionTextureEnabled;
  43468. },
  43469. set: function (value) {
  43470. if (StandardMaterial._RefractionTextureEnabled === value) {
  43471. return;
  43472. }
  43473. StandardMaterial._RefractionTextureEnabled = value;
  43474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43475. },
  43476. enumerable: true,
  43477. configurable: true
  43478. });
  43479. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43480. get: function () {
  43481. return StandardMaterial._ColorGradingTextureEnabled;
  43482. },
  43483. set: function (value) {
  43484. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43485. return;
  43486. }
  43487. StandardMaterial._ColorGradingTextureEnabled = value;
  43488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43494. get: function () {
  43495. return StandardMaterial._FresnelEnabled;
  43496. },
  43497. set: function (value) {
  43498. if (StandardMaterial._FresnelEnabled === value) {
  43499. return;
  43500. }
  43501. StandardMaterial._FresnelEnabled = value;
  43502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43503. },
  43504. enumerable: true,
  43505. configurable: true
  43506. });
  43507. // Flags used to enable or disable a type of texture for all Standard Materials
  43508. StandardMaterial._DiffuseTextureEnabled = true;
  43509. StandardMaterial._AmbientTextureEnabled = true;
  43510. StandardMaterial._OpacityTextureEnabled = true;
  43511. StandardMaterial._ReflectionTextureEnabled = true;
  43512. StandardMaterial._EmissiveTextureEnabled = true;
  43513. StandardMaterial._SpecularTextureEnabled = true;
  43514. StandardMaterial._BumpTextureEnabled = true;
  43515. StandardMaterial._LightmapTextureEnabled = true;
  43516. StandardMaterial._RefractionTextureEnabled = true;
  43517. StandardMaterial._ColorGradingTextureEnabled = true;
  43518. StandardMaterial._FresnelEnabled = true;
  43519. __decorate([
  43520. BABYLON.serializeAsTexture("diffuseTexture")
  43521. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43522. __decorate([
  43523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43524. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43525. __decorate([
  43526. BABYLON.serializeAsTexture("ambientTexture")
  43527. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43528. __decorate([
  43529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43530. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43531. __decorate([
  43532. BABYLON.serializeAsTexture("opacityTexture")
  43533. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43534. __decorate([
  43535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43536. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43537. __decorate([
  43538. BABYLON.serializeAsTexture("reflectionTexture")
  43539. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43540. __decorate([
  43541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43542. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43543. __decorate([
  43544. BABYLON.serializeAsTexture("emissiveTexture")
  43545. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43546. __decorate([
  43547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43548. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43549. __decorate([
  43550. BABYLON.serializeAsTexture("specularTexture")
  43551. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43552. __decorate([
  43553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43554. ], StandardMaterial.prototype, "specularTexture", void 0);
  43555. __decorate([
  43556. BABYLON.serializeAsTexture("bumpTexture")
  43557. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43558. __decorate([
  43559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43560. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43561. __decorate([
  43562. BABYLON.serializeAsTexture("lightmapTexture")
  43563. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43564. __decorate([
  43565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43566. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43567. __decorate([
  43568. BABYLON.serializeAsTexture("refractionTexture")
  43569. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43570. __decorate([
  43571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43572. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43573. __decorate([
  43574. BABYLON.serializeAsColor3("ambient")
  43575. ], StandardMaterial.prototype, "ambientColor", void 0);
  43576. __decorate([
  43577. BABYLON.serializeAsColor3("diffuse")
  43578. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43579. __decorate([
  43580. BABYLON.serializeAsColor3("specular")
  43581. ], StandardMaterial.prototype, "specularColor", void 0);
  43582. __decorate([
  43583. BABYLON.serializeAsColor3("emissive")
  43584. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43585. __decorate([
  43586. BABYLON.serialize()
  43587. ], StandardMaterial.prototype, "specularPower", void 0);
  43588. __decorate([
  43589. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43590. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43591. __decorate([
  43592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43593. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43594. __decorate([
  43595. BABYLON.serialize("useEmissiveAsIllumination")
  43596. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43597. __decorate([
  43598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43599. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43600. __decorate([
  43601. BABYLON.serialize("linkEmissiveWithDiffuse")
  43602. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43603. __decorate([
  43604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43605. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43606. __decorate([
  43607. BABYLON.serialize("useSpecularOverAlpha")
  43608. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43609. __decorate([
  43610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43611. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43612. __decorate([
  43613. BABYLON.serialize("useReflectionOverAlpha")
  43614. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43615. __decorate([
  43616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43617. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43618. __decorate([
  43619. BABYLON.serialize("disableLighting")
  43620. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43621. __decorate([
  43622. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43623. ], StandardMaterial.prototype, "disableLighting", void 0);
  43624. __decorate([
  43625. BABYLON.serialize("useObjectSpaceNormalMap")
  43626. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43627. __decorate([
  43628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43629. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43630. __decorate([
  43631. BABYLON.serialize("useParallax")
  43632. ], StandardMaterial.prototype, "_useParallax", void 0);
  43633. __decorate([
  43634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43635. ], StandardMaterial.prototype, "useParallax", void 0);
  43636. __decorate([
  43637. BABYLON.serialize("useParallaxOcclusion")
  43638. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43639. __decorate([
  43640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43641. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43642. __decorate([
  43643. BABYLON.serialize()
  43644. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43645. __decorate([
  43646. BABYLON.serialize("roughness")
  43647. ], StandardMaterial.prototype, "_roughness", void 0);
  43648. __decorate([
  43649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43650. ], StandardMaterial.prototype, "roughness", void 0);
  43651. __decorate([
  43652. BABYLON.serialize()
  43653. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43654. __decorate([
  43655. BABYLON.serialize()
  43656. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43657. __decorate([
  43658. BABYLON.serialize()
  43659. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43660. __decorate([
  43661. BABYLON.serialize("useLightmapAsShadowmap")
  43662. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43663. __decorate([
  43664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43665. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43666. __decorate([
  43667. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43668. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43669. __decorate([
  43670. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43671. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43672. __decorate([
  43673. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43674. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43675. __decorate([
  43676. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43677. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43678. __decorate([
  43679. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43680. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43681. __decorate([
  43682. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43683. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43684. __decorate([
  43685. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43686. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43687. __decorate([
  43688. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43689. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43690. __decorate([
  43691. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43692. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43693. __decorate([
  43694. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43695. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43696. __decorate([
  43697. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43698. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43699. __decorate([
  43700. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43701. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43702. __decorate([
  43703. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43704. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43705. __decorate([
  43706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43707. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43708. __decorate([
  43709. BABYLON.serialize("maxSimultaneousLights")
  43710. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43711. __decorate([
  43712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43713. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43714. __decorate([
  43715. BABYLON.serialize("invertNormalMapX")
  43716. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43717. __decorate([
  43718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43719. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43720. __decorate([
  43721. BABYLON.serialize("invertNormalMapY")
  43722. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43723. __decorate([
  43724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43725. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43726. __decorate([
  43727. BABYLON.serialize("twoSidedLighting")
  43728. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43729. __decorate([
  43730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43731. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43732. __decorate([
  43733. BABYLON.serialize()
  43734. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43735. return StandardMaterial;
  43736. }(BABYLON.PushMaterial));
  43737. BABYLON.StandardMaterial = StandardMaterial;
  43738. })(BABYLON || (BABYLON = {}));
  43739. //# sourceMappingURL=babylon.standardMaterial.js.map
  43740. var BABYLON;
  43741. (function (BABYLON) {
  43742. /**
  43743. * Manages the defines for the PBR Material.
  43744. * @ignoreChildren
  43745. */
  43746. var PBRMaterialDefines = /** @class */ (function (_super) {
  43747. __extends(PBRMaterialDefines, _super);
  43748. /**
  43749. * Initializes the PBR Material defines.
  43750. */
  43751. function PBRMaterialDefines() {
  43752. var _this = _super.call(this) || this;
  43753. _this.PBR = true;
  43754. _this.MAINUV1 = false;
  43755. _this.MAINUV2 = false;
  43756. _this.UV1 = false;
  43757. _this.UV2 = false;
  43758. _this.ALBEDO = false;
  43759. _this.ALBEDODIRECTUV = 0;
  43760. _this.VERTEXCOLOR = false;
  43761. _this.AMBIENT = false;
  43762. _this.AMBIENTDIRECTUV = 0;
  43763. _this.AMBIENTINGRAYSCALE = false;
  43764. _this.OPACITY = false;
  43765. _this.VERTEXALPHA = false;
  43766. _this.OPACITYDIRECTUV = 0;
  43767. _this.OPACITYRGB = false;
  43768. _this.ALPHATEST = false;
  43769. _this.DEPTHPREPASS = false;
  43770. _this.ALPHABLEND = false;
  43771. _this.ALPHAFROMALBEDO = false;
  43772. _this.ALPHATESTVALUE = "0.5";
  43773. _this.SPECULAROVERALPHA = false;
  43774. _this.RADIANCEOVERALPHA = false;
  43775. _this.ALPHAFRESNEL = false;
  43776. _this.LINEARALPHAFRESNEL = false;
  43777. _this.PREMULTIPLYALPHA = false;
  43778. _this.EMISSIVE = false;
  43779. _this.EMISSIVEDIRECTUV = 0;
  43780. _this.REFLECTIVITY = false;
  43781. _this.REFLECTIVITYDIRECTUV = 0;
  43782. _this.SPECULARTERM = false;
  43783. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43784. _this.MICROSURFACEAUTOMATIC = false;
  43785. _this.LODBASEDMICROSFURACE = false;
  43786. _this.MICROSURFACEMAP = false;
  43787. _this.MICROSURFACEMAPDIRECTUV = 0;
  43788. _this.METALLICWORKFLOW = false;
  43789. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43790. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43791. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43792. _this.AOSTOREINMETALMAPRED = false;
  43793. _this.ENVIRONMENTBRDF = false;
  43794. _this.NORMAL = false;
  43795. _this.TANGENT = false;
  43796. _this.BUMP = false;
  43797. _this.BUMPDIRECTUV = 0;
  43798. _this.OBJECTSPACE_NORMALMAP = false;
  43799. _this.PARALLAX = false;
  43800. _this.PARALLAXOCCLUSION = false;
  43801. _this.NORMALXYSCALE = true;
  43802. _this.LIGHTMAP = false;
  43803. _this.LIGHTMAPDIRECTUV = 0;
  43804. _this.USELIGHTMAPASSHADOWMAP = false;
  43805. _this.GAMMALIGHTMAP = false;
  43806. _this.REFLECTION = false;
  43807. _this.REFLECTIONMAP_3D = false;
  43808. _this.REFLECTIONMAP_SPHERICAL = false;
  43809. _this.REFLECTIONMAP_PLANAR = false;
  43810. _this.REFLECTIONMAP_CUBIC = false;
  43811. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43812. _this.REFLECTIONMAP_PROJECTION = false;
  43813. _this.REFLECTIONMAP_SKYBOX = false;
  43814. _this.REFLECTIONMAP_EXPLICIT = false;
  43815. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43816. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43817. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43818. _this.INVERTCUBICMAP = false;
  43819. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43820. _this.USESPHERICALINVERTEX = false;
  43821. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43822. _this.LODINREFLECTIONALPHA = false;
  43823. _this.GAMMAREFLECTION = false;
  43824. _this.RADIANCEOCCLUSION = false;
  43825. _this.HORIZONOCCLUSION = false;
  43826. _this.REFRACTION = false;
  43827. _this.REFRACTIONMAP_3D = false;
  43828. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43829. _this.LODINREFRACTIONALPHA = false;
  43830. _this.GAMMAREFRACTION = false;
  43831. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43832. _this.INSTANCES = false;
  43833. _this.NUM_BONE_INFLUENCERS = 0;
  43834. _this.BonesPerMesh = 0;
  43835. _this.NONUNIFORMSCALING = false;
  43836. _this.MORPHTARGETS = false;
  43837. _this.MORPHTARGETS_NORMAL = false;
  43838. _this.MORPHTARGETS_TANGENT = false;
  43839. _this.NUM_MORPH_INFLUENCERS = 0;
  43840. _this.IMAGEPROCESSING = false;
  43841. _this.VIGNETTE = false;
  43842. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43843. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43844. _this.TONEMAPPING = false;
  43845. _this.CONTRAST = false;
  43846. _this.COLORCURVES = false;
  43847. _this.COLORGRADING = false;
  43848. _this.COLORGRADING3D = false;
  43849. _this.SAMPLER3DGREENDEPTH = false;
  43850. _this.SAMPLER3DBGRMAP = false;
  43851. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43852. _this.EXPOSURE = false;
  43853. _this.USEPHYSICALLIGHTFALLOFF = false;
  43854. _this.TWOSIDEDLIGHTING = false;
  43855. _this.SHADOWFLOAT = false;
  43856. _this.CLIPPLANE = false;
  43857. _this.POINTSIZE = false;
  43858. _this.FOG = false;
  43859. _this.LOGARITHMICDEPTH = false;
  43860. _this.FORCENORMALFORWARD = false;
  43861. _this.GEOMETRYAA = false;
  43862. _this.UNLIT = false;
  43863. _this.rebuild();
  43864. return _this;
  43865. }
  43866. /**
  43867. * Resets the PBR Material defines.
  43868. */
  43869. PBRMaterialDefines.prototype.reset = function () {
  43870. _super.prototype.reset.call(this);
  43871. this.ALPHATESTVALUE = "0.5";
  43872. this.PBR = true;
  43873. };
  43874. return PBRMaterialDefines;
  43875. }(BABYLON.MaterialDefines));
  43876. /**
  43877. * The Physically based material base class of BJS.
  43878. *
  43879. * This offers the main features of a standard PBR material.
  43880. * For more information, please refer to the documentation :
  43881. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43882. */
  43883. var PBRBaseMaterial = /** @class */ (function (_super) {
  43884. __extends(PBRBaseMaterial, _super);
  43885. /**
  43886. * Instantiates a new PBRMaterial instance.
  43887. *
  43888. * @param name The material name
  43889. * @param scene The scene the material will be use in.
  43890. */
  43891. function PBRBaseMaterial(name, scene) {
  43892. var _this = _super.call(this, name, scene) || this;
  43893. /**
  43894. * Intensity of the direct lights e.g. the four lights available in your scene.
  43895. * This impacts both the direct diffuse and specular highlights.
  43896. */
  43897. _this._directIntensity = 1.0;
  43898. /**
  43899. * Intensity of the emissive part of the material.
  43900. * This helps controlling the emissive effect without modifying the emissive color.
  43901. */
  43902. _this._emissiveIntensity = 1.0;
  43903. /**
  43904. * Intensity of the environment e.g. how much the environment will light the object
  43905. * either through harmonics for rough material or through the refelction for shiny ones.
  43906. */
  43907. _this._environmentIntensity = 1.0;
  43908. /**
  43909. * This is a special control allowing the reduction of the specular highlights coming from the
  43910. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43911. */
  43912. _this._specularIntensity = 1.0;
  43913. /**
  43914. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43915. */
  43916. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43917. /**
  43918. * Debug Control allowing disabling the bump map on this material.
  43919. */
  43920. _this._disableBumpMap = false;
  43921. /**
  43922. * AKA Occlusion Texture Intensity in other nomenclature.
  43923. */
  43924. _this._ambientTextureStrength = 1.0;
  43925. /**
  43926. * The color of a material in ambient lighting.
  43927. */
  43928. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43929. /**
  43930. * AKA Diffuse Color in other nomenclature.
  43931. */
  43932. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43933. /**
  43934. * AKA Specular Color in other nomenclature.
  43935. */
  43936. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43937. /**
  43938. * The color applied when light is reflected from a material.
  43939. */
  43940. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43941. /**
  43942. * The color applied when light is emitted from a material.
  43943. */
  43944. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43945. /**
  43946. * AKA Glossiness in other nomenclature.
  43947. */
  43948. _this._microSurface = 0.9;
  43949. /**
  43950. * source material index of refraction (IOR)' / 'destination material IOR.
  43951. */
  43952. _this._indexOfRefraction = 0.66;
  43953. /**
  43954. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43955. */
  43956. _this._invertRefractionY = false;
  43957. /**
  43958. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43959. * Materials half opaque for instance using refraction could benefit from this control.
  43960. */
  43961. _this._linkRefractionWithTransparency = false;
  43962. /**
  43963. * Specifies that the material will use the light map as a show map.
  43964. */
  43965. _this._useLightmapAsShadowmap = false;
  43966. /**
  43967. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43968. * makes the reflect vector face the model (under horizon).
  43969. */
  43970. _this._useHorizonOcclusion = true;
  43971. /**
  43972. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43973. * too much the area relying on ambient texture to define their ambient occlusion.
  43974. */
  43975. _this._useRadianceOcclusion = true;
  43976. /**
  43977. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43978. */
  43979. _this._useAlphaFromAlbedoTexture = false;
  43980. /**
  43981. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43982. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43983. */
  43984. _this._useSpecularOverAlpha = true;
  43985. /**
  43986. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43987. */
  43988. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43989. /**
  43990. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43991. */
  43992. _this._useRoughnessFromMetallicTextureAlpha = true;
  43993. /**
  43994. * Specifies if the metallic texture contains the roughness information in its green channel.
  43995. */
  43996. _this._useRoughnessFromMetallicTextureGreen = false;
  43997. /**
  43998. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43999. */
  44000. _this._useMetallnessFromMetallicTextureBlue = false;
  44001. /**
  44002. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44003. */
  44004. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44005. /**
  44006. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44007. */
  44008. _this._useAmbientInGrayScale = false;
  44009. /**
  44010. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44011. * The material will try to infer what glossiness each pixel should be.
  44012. */
  44013. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44014. /**
  44015. * BJS is using an harcoded light falloff based on a manually sets up range.
  44016. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44017. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44018. */
  44019. _this._usePhysicalLightFalloff = true;
  44020. /**
  44021. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44022. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44023. */
  44024. _this._useRadianceOverAlpha = true;
  44025. /**
  44026. * Allows using an object space normal map (instead of tangent space).
  44027. */
  44028. _this._useObjectSpaceNormalMap = false;
  44029. /**
  44030. * Allows using the bump map in parallax mode.
  44031. */
  44032. _this._useParallax = false;
  44033. /**
  44034. * Allows using the bump map in parallax occlusion mode.
  44035. */
  44036. _this._useParallaxOcclusion = false;
  44037. /**
  44038. * Controls the scale bias of the parallax mode.
  44039. */
  44040. _this._parallaxScaleBias = 0.05;
  44041. /**
  44042. * If sets to true, disables all the lights affecting the material.
  44043. */
  44044. _this._disableLighting = false;
  44045. /**
  44046. * Number of Simultaneous lights allowed on the material.
  44047. */
  44048. _this._maxSimultaneousLights = 4;
  44049. /**
  44050. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44051. */
  44052. _this._invertNormalMapX = false;
  44053. /**
  44054. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44055. */
  44056. _this._invertNormalMapY = false;
  44057. /**
  44058. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44059. */
  44060. _this._twoSidedLighting = false;
  44061. /**
  44062. * Defines the alpha limits in alpha test mode.
  44063. */
  44064. _this._alphaCutOff = 0.4;
  44065. /**
  44066. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44067. */
  44068. _this._forceAlphaTest = false;
  44069. /**
  44070. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44071. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44072. */
  44073. _this._useAlphaFresnel = false;
  44074. /**
  44075. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44076. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44077. */
  44078. _this._useLinearAlphaFresnel = false;
  44079. /**
  44080. * The transparency mode of the material.
  44081. */
  44082. _this._transparencyMode = null;
  44083. /**
  44084. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44085. * from cos thetav and roughness:
  44086. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44087. */
  44088. _this._environmentBRDFTexture = null;
  44089. /**
  44090. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44091. */
  44092. _this._forceIrradianceInFragment = false;
  44093. /**
  44094. * Force normal to face away from face.
  44095. */
  44096. _this._forceNormalForward = false;
  44097. /**
  44098. * Enables specular anti aliasing in the PBR shader.
  44099. * It will both interacts on the Geometry for analytical and IBL lighting.
  44100. * It also prefilter the roughness map based on the bump values.
  44101. */
  44102. _this._enableSpecularAntiAliasing = false;
  44103. /**
  44104. * Stores the available render targets.
  44105. */
  44106. _this._renderTargets = new BABYLON.SmartArray(16);
  44107. /**
  44108. * Sets the global ambient color for the material used in lighting calculations.
  44109. */
  44110. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44111. /**
  44112. * If set to true, no lighting calculations will be applied.
  44113. */
  44114. _this._unlit = false;
  44115. // Setup the default processing configuration to the scene.
  44116. _this._attachImageProcessingConfiguration(null);
  44117. _this.getRenderTargetTextures = function () {
  44118. _this._renderTargets.reset();
  44119. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44120. _this._renderTargets.push(_this._reflectionTexture);
  44121. }
  44122. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44123. _this._renderTargets.push(_this._refractionTexture);
  44124. }
  44125. return _this._renderTargets;
  44126. };
  44127. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44128. return _this;
  44129. }
  44130. /**
  44131. * Attaches a new image processing configuration to the PBR Material.
  44132. * @param configuration
  44133. */
  44134. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44135. var _this = this;
  44136. if (configuration === this._imageProcessingConfiguration) {
  44137. return;
  44138. }
  44139. // Detaches observer.
  44140. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44141. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44142. }
  44143. // Pick the scene configuration if needed.
  44144. if (!configuration) {
  44145. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44146. }
  44147. else {
  44148. this._imageProcessingConfiguration = configuration;
  44149. }
  44150. // Attaches observer.
  44151. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44152. _this._markAllSubMeshesAsImageProcessingDirty();
  44153. });
  44154. };
  44155. /**
  44156. * Gets the name of the material class.
  44157. */
  44158. PBRBaseMaterial.prototype.getClassName = function () {
  44159. return "PBRBaseMaterial";
  44160. };
  44161. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44162. /**
  44163. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44164. */
  44165. get: function () {
  44166. return this._useLogarithmicDepth;
  44167. },
  44168. /**
  44169. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44170. */
  44171. set: function (value) {
  44172. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44173. },
  44174. enumerable: true,
  44175. configurable: true
  44176. });
  44177. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44178. /**
  44179. * Gets the current transparency mode.
  44180. */
  44181. get: function () {
  44182. return this._transparencyMode;
  44183. },
  44184. /**
  44185. * Sets the transparency mode of the material.
  44186. */
  44187. set: function (value) {
  44188. if (this._transparencyMode === value) {
  44189. return;
  44190. }
  44191. this._transparencyMode = value;
  44192. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44193. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44194. },
  44195. enumerable: true,
  44196. configurable: true
  44197. });
  44198. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44199. /**
  44200. * Returns true if alpha blending should be disabled.
  44201. */
  44202. get: function () {
  44203. return (this._linkRefractionWithTransparency ||
  44204. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44205. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44206. },
  44207. enumerable: true,
  44208. configurable: true
  44209. });
  44210. /**
  44211. * Specifies whether or not this material should be rendered in alpha blend mode.
  44212. */
  44213. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44214. if (this._disableAlphaBlending) {
  44215. return false;
  44216. }
  44217. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44218. };
  44219. /**
  44220. * Specifies if the mesh will require alpha blending.
  44221. * @param mesh - BJS mesh.
  44222. */
  44223. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44224. if (this._disableAlphaBlending) {
  44225. return false;
  44226. }
  44227. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44228. };
  44229. /**
  44230. * Specifies whether or not this material should be rendered in alpha test mode.
  44231. */
  44232. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44233. if (this._forceAlphaTest) {
  44234. return true;
  44235. }
  44236. if (this._linkRefractionWithTransparency) {
  44237. return false;
  44238. }
  44239. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44240. };
  44241. /**
  44242. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44243. */
  44244. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44245. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44246. };
  44247. /**
  44248. * Gets the texture used for the alpha test.
  44249. */
  44250. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44251. return this._albedoTexture;
  44252. };
  44253. /**
  44254. * Specifies that the submesh is ready to be used.
  44255. * @param mesh - BJS mesh.
  44256. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44257. * @param useInstances - Specifies that instances should be used.
  44258. * @returns - boolean indicating that the submesh is ready or not.
  44259. */
  44260. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44261. if (subMesh.effect && this.isFrozen) {
  44262. if (this._wasPreviouslyReady) {
  44263. return true;
  44264. }
  44265. }
  44266. if (!subMesh._materialDefines) {
  44267. subMesh._materialDefines = new PBRMaterialDefines();
  44268. }
  44269. var defines = subMesh._materialDefines;
  44270. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44271. if (defines._renderId === this.getScene().getRenderId()) {
  44272. return true;
  44273. }
  44274. }
  44275. var scene = this.getScene();
  44276. var engine = scene.getEngine();
  44277. if (defines._areTexturesDirty) {
  44278. if (scene.texturesEnabled) {
  44279. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44280. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44281. return false;
  44282. }
  44283. }
  44284. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44285. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44286. return false;
  44287. }
  44288. }
  44289. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44290. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44291. return false;
  44292. }
  44293. }
  44294. var reflectionTexture = this._getReflectionTexture();
  44295. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44296. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44297. return false;
  44298. }
  44299. }
  44300. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44301. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44302. return false;
  44303. }
  44304. }
  44305. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44306. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44307. return false;
  44308. }
  44309. }
  44310. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44311. if (this._metallicTexture) {
  44312. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44313. return false;
  44314. }
  44315. }
  44316. else if (this._reflectivityTexture) {
  44317. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44318. return false;
  44319. }
  44320. }
  44321. if (this._microSurfaceTexture) {
  44322. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44323. return false;
  44324. }
  44325. }
  44326. }
  44327. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44328. // Bump texture cannot be not blocking.
  44329. if (!this._bumpTexture.isReady()) {
  44330. return false;
  44331. }
  44332. }
  44333. var refractionTexture = this._getRefractionTexture();
  44334. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44335. if (!refractionTexture.isReadyOrNotBlocking()) {
  44336. return false;
  44337. }
  44338. }
  44339. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44340. // This is blocking.
  44341. if (!this._environmentBRDFTexture.isReady()) {
  44342. return false;
  44343. }
  44344. }
  44345. }
  44346. }
  44347. if (defines._areImageProcessingDirty) {
  44348. if (!this._imageProcessingConfiguration.isReady()) {
  44349. return false;
  44350. }
  44351. }
  44352. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44353. mesh.createNormals(true);
  44354. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44355. }
  44356. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44357. if (effect) {
  44358. scene.resetCachedMaterial();
  44359. subMesh.setEffect(effect, defines);
  44360. this.buildUniformLayout();
  44361. }
  44362. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44363. return false;
  44364. }
  44365. defines._renderId = scene.getRenderId();
  44366. this._wasPreviouslyReady = true;
  44367. return true;
  44368. };
  44369. /**
  44370. * Specifies if the material uses metallic roughness workflow.
  44371. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44372. */
  44373. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44374. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44375. return true;
  44376. }
  44377. return false;
  44378. };
  44379. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44380. if (onCompiled === void 0) { onCompiled = null; }
  44381. if (onError === void 0) { onError = null; }
  44382. if (useInstances === void 0) { useInstances = null; }
  44383. if (useClipPlane === void 0) { useClipPlane = null; }
  44384. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44385. if (!defines.isDirty) {
  44386. return null;
  44387. }
  44388. defines.markAsProcessed();
  44389. var scene = this.getScene();
  44390. var engine = scene.getEngine();
  44391. // Fallbacks
  44392. var fallbacks = new BABYLON.EffectFallbacks();
  44393. var fallbackRank = 0;
  44394. if (defines.USESPHERICALINVERTEX) {
  44395. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44396. }
  44397. if (defines.FOG) {
  44398. fallbacks.addFallback(fallbackRank, "FOG");
  44399. }
  44400. if (defines.POINTSIZE) {
  44401. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44402. }
  44403. if (defines.LOGARITHMICDEPTH) {
  44404. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44405. }
  44406. if (defines.PARALLAX) {
  44407. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44408. }
  44409. if (defines.PARALLAXOCCLUSION) {
  44410. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44411. }
  44412. if (defines.ENVIRONMENTBRDF) {
  44413. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44414. }
  44415. if (defines.TANGENT) {
  44416. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44417. }
  44418. if (defines.BUMP) {
  44419. fallbacks.addFallback(fallbackRank++, "BUMP");
  44420. }
  44421. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44422. if (defines.SPECULARTERM) {
  44423. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44424. }
  44425. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44426. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44427. }
  44428. if (defines.LIGHTMAP) {
  44429. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44430. }
  44431. if (defines.NORMAL) {
  44432. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44433. }
  44434. if (defines.AMBIENT) {
  44435. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44436. }
  44437. if (defines.EMISSIVE) {
  44438. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44439. }
  44440. if (defines.VERTEXCOLOR) {
  44441. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44442. }
  44443. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44444. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44445. }
  44446. if (defines.MORPHTARGETS) {
  44447. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44448. }
  44449. //Attributes
  44450. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44451. if (defines.NORMAL) {
  44452. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44453. }
  44454. if (defines.TANGENT) {
  44455. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44456. }
  44457. if (defines.UV1) {
  44458. attribs.push(BABYLON.VertexBuffer.UVKind);
  44459. }
  44460. if (defines.UV2) {
  44461. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44462. }
  44463. if (defines.VERTEXCOLOR) {
  44464. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44465. }
  44466. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44467. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44468. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44469. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44470. "vFogInfos", "vFogColor", "pointSize",
  44471. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44472. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44473. "mBones",
  44474. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44475. "vLightingIntensity",
  44476. "logarithmicDepthConstant",
  44477. "vSphericalX", "vSphericalY", "vSphericalZ",
  44478. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44479. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44480. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44481. "vTangentSpaceParams"
  44482. ];
  44483. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44484. "bumpSampler", "lightmapSampler", "opacitySampler",
  44485. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44486. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44487. "microSurfaceSampler", "environmentBrdfSampler"];
  44488. var uniformBuffers = ["Material", "Scene"];
  44489. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44490. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44491. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44492. uniformsNames: uniforms,
  44493. uniformBuffersNames: uniformBuffers,
  44494. samplers: samplers,
  44495. defines: defines,
  44496. maxSimultaneousLights: this._maxSimultaneousLights
  44497. });
  44498. var join = defines.toString();
  44499. return engine.createEffect("pbr", {
  44500. attributes: attribs,
  44501. uniformsNames: uniforms,
  44502. uniformBuffersNames: uniformBuffers,
  44503. samplers: samplers,
  44504. defines: join,
  44505. fallbacks: fallbacks,
  44506. onCompiled: onCompiled,
  44507. onError: onError,
  44508. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44509. }, engine);
  44510. };
  44511. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44512. if (useInstances === void 0) { useInstances = null; }
  44513. if (useClipPlane === void 0) { useClipPlane = null; }
  44514. var scene = this.getScene();
  44515. var engine = scene.getEngine();
  44516. // Lights
  44517. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44518. defines._needNormals = true;
  44519. // Textures
  44520. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44521. if (defines._areTexturesDirty) {
  44522. defines._needUVs = false;
  44523. if (scene.texturesEnabled) {
  44524. if (scene.getEngine().getCaps().textureLOD) {
  44525. defines.LODBASEDMICROSFURACE = true;
  44526. }
  44527. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44528. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44529. }
  44530. else {
  44531. defines.ALBEDO = false;
  44532. }
  44533. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44535. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44536. }
  44537. else {
  44538. defines.AMBIENT = false;
  44539. }
  44540. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44542. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44543. }
  44544. else {
  44545. defines.OPACITY = false;
  44546. }
  44547. var reflectionTexture = this._getReflectionTexture();
  44548. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44549. defines.REFLECTION = true;
  44550. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44551. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44552. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44553. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44554. defines.INVERTCUBICMAP = true;
  44555. }
  44556. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44557. switch (reflectionTexture.coordinatesMode) {
  44558. case BABYLON.Texture.CUBIC_MODE:
  44559. case BABYLON.Texture.INVCUBIC_MODE:
  44560. defines.REFLECTIONMAP_CUBIC = true;
  44561. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44562. break;
  44563. case BABYLON.Texture.EXPLICIT_MODE:
  44564. defines.REFLECTIONMAP_EXPLICIT = true;
  44565. break;
  44566. case BABYLON.Texture.PLANAR_MODE:
  44567. defines.REFLECTIONMAP_PLANAR = true;
  44568. break;
  44569. case BABYLON.Texture.PROJECTION_MODE:
  44570. defines.REFLECTIONMAP_PROJECTION = true;
  44571. break;
  44572. case BABYLON.Texture.SKYBOX_MODE:
  44573. defines.REFLECTIONMAP_SKYBOX = true;
  44574. break;
  44575. case BABYLON.Texture.SPHERICAL_MODE:
  44576. defines.REFLECTIONMAP_SPHERICAL = true;
  44577. break;
  44578. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44579. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44580. break;
  44581. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44582. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44583. break;
  44584. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44585. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44586. break;
  44587. }
  44588. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44589. if (reflectionTexture.sphericalPolynomial) {
  44590. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44591. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44592. defines.USESPHERICALINVERTEX = false;
  44593. }
  44594. else {
  44595. defines.USESPHERICALINVERTEX = true;
  44596. }
  44597. }
  44598. }
  44599. }
  44600. else {
  44601. defines.REFLECTION = false;
  44602. defines.REFLECTIONMAP_3D = false;
  44603. defines.REFLECTIONMAP_SPHERICAL = false;
  44604. defines.REFLECTIONMAP_PLANAR = false;
  44605. defines.REFLECTIONMAP_CUBIC = false;
  44606. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44607. defines.REFLECTIONMAP_PROJECTION = false;
  44608. defines.REFLECTIONMAP_SKYBOX = false;
  44609. defines.REFLECTIONMAP_EXPLICIT = false;
  44610. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44611. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44612. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44613. defines.INVERTCUBICMAP = false;
  44614. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44615. defines.USESPHERICALINVERTEX = false;
  44616. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44617. defines.LODINREFLECTIONALPHA = false;
  44618. defines.GAMMAREFLECTION = false;
  44619. }
  44620. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44621. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44622. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44623. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44624. }
  44625. else {
  44626. defines.LIGHTMAP = false;
  44627. }
  44628. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44629. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44630. }
  44631. else {
  44632. defines.EMISSIVE = false;
  44633. }
  44634. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44635. if (this._metallicTexture) {
  44636. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44637. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44638. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44639. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44640. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44641. }
  44642. else if (this._reflectivityTexture) {
  44643. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44644. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44645. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44646. }
  44647. else {
  44648. defines.REFLECTIVITY = false;
  44649. }
  44650. if (this._microSurfaceTexture) {
  44651. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44652. }
  44653. else {
  44654. defines.MICROSURFACEMAP = false;
  44655. }
  44656. }
  44657. else {
  44658. defines.REFLECTIVITY = false;
  44659. defines.MICROSURFACEMAP = false;
  44660. }
  44661. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44662. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44663. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44664. defines.PARALLAX = true;
  44665. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44666. }
  44667. else {
  44668. defines.PARALLAX = false;
  44669. }
  44670. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44671. }
  44672. else {
  44673. defines.BUMP = false;
  44674. }
  44675. var refractionTexture = this._getRefractionTexture();
  44676. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44677. defines.REFRACTION = true;
  44678. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44679. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44680. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44681. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44682. if (this._linkRefractionWithTransparency) {
  44683. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44684. }
  44685. }
  44686. else {
  44687. defines.REFRACTION = false;
  44688. }
  44689. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44690. defines.ENVIRONMENTBRDF = true;
  44691. }
  44692. else {
  44693. defines.ENVIRONMENTBRDF = false;
  44694. }
  44695. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44696. defines.ALPHAFROMALBEDO = true;
  44697. }
  44698. else {
  44699. defines.ALPHAFROMALBEDO = false;
  44700. }
  44701. }
  44702. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44703. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44704. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44705. if (!this.backFaceCulling && this._twoSidedLighting) {
  44706. defines.TWOSIDEDLIGHTING = true;
  44707. }
  44708. else {
  44709. defines.TWOSIDEDLIGHTING = false;
  44710. }
  44711. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44712. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44713. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44714. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44715. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44716. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44717. }
  44718. if (defines._areImageProcessingDirty) {
  44719. this._imageProcessingConfiguration.prepareDefines(defines);
  44720. }
  44721. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44722. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44723. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44724. // Misc.
  44725. if (defines._areMiscDirty) {
  44726. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44727. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44728. }
  44729. // Values that need to be evaluated on every frame
  44730. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44731. // Attribs
  44732. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44733. };
  44734. /**
  44735. * Force shader compilation
  44736. */
  44737. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44738. var _this = this;
  44739. var localOptions = __assign({ clipPlane: false }, options);
  44740. var defines = new PBRMaterialDefines();
  44741. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44742. if (effect.isReady()) {
  44743. if (onCompiled) {
  44744. onCompiled(this);
  44745. }
  44746. }
  44747. else {
  44748. effect.onCompileObservable.add(function () {
  44749. if (onCompiled) {
  44750. onCompiled(_this);
  44751. }
  44752. });
  44753. }
  44754. };
  44755. /**
  44756. * Initializes the uniform buffer layout for the shader.
  44757. */
  44758. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44759. // Order is important !
  44760. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44761. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44762. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44763. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44764. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44765. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44766. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44767. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44768. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44769. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44770. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44771. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44772. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44773. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44774. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44775. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44776. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44777. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44778. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44779. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44780. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44781. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44782. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44783. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44784. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44785. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44786. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44787. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44788. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44789. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44790. this._uniformBuffer.addUniform("pointSize", 1);
  44791. this._uniformBuffer.create();
  44792. };
  44793. /**
  44794. * Unbinds the textures.
  44795. */
  44796. PBRBaseMaterial.prototype.unbind = function () {
  44797. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44798. this._uniformBuffer.setTexture("reflectionSampler", null);
  44799. }
  44800. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44801. this._uniformBuffer.setTexture("refractionSampler", null);
  44802. }
  44803. _super.prototype.unbind.call(this);
  44804. };
  44805. /**
  44806. * Binds the submesh data.
  44807. * @param world - The world matrix.
  44808. * @param mesh - The BJS mesh.
  44809. * @param subMesh - A submesh of the BJS mesh.
  44810. */
  44811. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44812. var scene = this.getScene();
  44813. var defines = subMesh._materialDefines;
  44814. if (!defines) {
  44815. return;
  44816. }
  44817. var effect = subMesh.effect;
  44818. if (!effect) {
  44819. return;
  44820. }
  44821. this._activeEffect = effect;
  44822. // Matrices
  44823. this.bindOnlyWorldMatrix(world);
  44824. // Normal Matrix
  44825. if (defines.OBJECTSPACE_NORMALMAP) {
  44826. world.toNormalMatrix(this._normalMatrix);
  44827. this.bindOnlyNormalMatrix(this._normalMatrix);
  44828. }
  44829. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44830. // Bones
  44831. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44832. var reflectionTexture = null;
  44833. if (mustRebind) {
  44834. this._uniformBuffer.bindToEffect(effect, "Material");
  44835. this.bindViewProjection(effect);
  44836. reflectionTexture = this._getReflectionTexture();
  44837. var refractionTexture = this._getRefractionTexture();
  44838. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44839. // Texture uniforms
  44840. if (scene.texturesEnabled) {
  44841. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44842. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44843. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44844. }
  44845. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44846. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44847. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44848. }
  44849. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44850. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44851. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44852. }
  44853. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44854. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44855. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44856. if (reflectionTexture.boundingBoxSize) {
  44857. var cubeTexture = reflectionTexture;
  44858. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44859. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44860. }
  44861. var polynomials = reflectionTexture.sphericalPolynomial;
  44862. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44863. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44864. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44865. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44866. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44867. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44868. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44869. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44870. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44871. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44872. }
  44873. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44874. }
  44875. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44876. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44877. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44878. }
  44879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44880. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44881. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44882. }
  44883. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44884. if (this._metallicTexture) {
  44885. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44886. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44887. }
  44888. else if (this._reflectivityTexture) {
  44889. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44890. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44891. }
  44892. if (this._microSurfaceTexture) {
  44893. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44894. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44895. }
  44896. }
  44897. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44898. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44899. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44900. if (scene._mirroredCameraPosition) {
  44901. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44902. }
  44903. else {
  44904. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44905. }
  44906. }
  44907. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44908. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44909. var depth = 1.0;
  44910. if (!refractionTexture.isCube) {
  44911. if (refractionTexture.depth) {
  44912. depth = refractionTexture.depth;
  44913. }
  44914. }
  44915. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44916. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44917. }
  44918. }
  44919. // Point size
  44920. if (this.pointsCloud) {
  44921. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44922. }
  44923. // Colors
  44924. if (defines.METALLICWORKFLOW) {
  44925. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44926. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44927. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44928. }
  44929. else {
  44930. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44931. }
  44932. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44933. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44934. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44935. // Misc
  44936. this._lightingInfos.x = this._directIntensity;
  44937. this._lightingInfos.y = this._emissiveIntensity;
  44938. this._lightingInfos.z = this._environmentIntensity;
  44939. this._lightingInfos.w = this._specularIntensity;
  44940. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44941. }
  44942. // Textures
  44943. if (scene.texturesEnabled) {
  44944. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44945. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44946. }
  44947. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44948. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44949. }
  44950. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44951. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44952. }
  44953. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44954. if (defines.LODBASEDMICROSFURACE) {
  44955. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44956. }
  44957. else {
  44958. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44959. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44960. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44961. }
  44962. }
  44963. if (defines.ENVIRONMENTBRDF) {
  44964. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44965. }
  44966. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44967. if (defines.LODBASEDMICROSFURACE) {
  44968. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44969. }
  44970. else {
  44971. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44972. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44973. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44974. }
  44975. }
  44976. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44977. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44978. }
  44979. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44980. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44981. }
  44982. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44983. if (this._metallicTexture) {
  44984. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44985. }
  44986. else if (this._reflectivityTexture) {
  44987. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44988. }
  44989. if (this._microSurfaceTexture) {
  44990. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44991. }
  44992. }
  44993. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44994. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44995. }
  44996. }
  44997. // Clip plane
  44998. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44999. // Colors
  45000. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45001. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45002. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45003. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45004. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45005. }
  45006. if (mustRebind || !this.isFrozen) {
  45007. // Lights
  45008. if (scene.lightsEnabled && !this._disableLighting) {
  45009. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45010. }
  45011. // View
  45012. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45013. this.bindView(effect);
  45014. }
  45015. // Fog
  45016. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45017. // Morph targets
  45018. if (defines.NUM_MORPH_INFLUENCERS) {
  45019. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45020. }
  45021. // image processing
  45022. this._imageProcessingConfiguration.bind(this._activeEffect);
  45023. // Log. depth
  45024. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45025. }
  45026. this._uniformBuffer.update();
  45027. this._afterBind(mesh);
  45028. };
  45029. /**
  45030. * Returns the animatable textures.
  45031. * @returns - Array of animatable textures.
  45032. */
  45033. PBRBaseMaterial.prototype.getAnimatables = function () {
  45034. var results = [];
  45035. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45036. results.push(this._albedoTexture);
  45037. }
  45038. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45039. results.push(this._ambientTexture);
  45040. }
  45041. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45042. results.push(this._opacityTexture);
  45043. }
  45044. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45045. results.push(this._reflectionTexture);
  45046. }
  45047. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45048. results.push(this._emissiveTexture);
  45049. }
  45050. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45051. results.push(this._metallicTexture);
  45052. }
  45053. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45054. results.push(this._reflectivityTexture);
  45055. }
  45056. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45057. results.push(this._bumpTexture);
  45058. }
  45059. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45060. results.push(this._lightmapTexture);
  45061. }
  45062. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45063. results.push(this._refractionTexture);
  45064. }
  45065. return results;
  45066. };
  45067. /**
  45068. * Returns the texture used for reflections.
  45069. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45070. */
  45071. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45072. if (this._reflectionTexture) {
  45073. return this._reflectionTexture;
  45074. }
  45075. return this.getScene().environmentTexture;
  45076. };
  45077. /**
  45078. * Returns the texture used for refraction or null if none is used.
  45079. * @returns - Refection texture if present. If no refraction texture and refraction
  45080. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45081. */
  45082. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45083. if (this._refractionTexture) {
  45084. return this._refractionTexture;
  45085. }
  45086. if (this._linkRefractionWithTransparency) {
  45087. return this.getScene().environmentTexture;
  45088. }
  45089. return null;
  45090. };
  45091. /**
  45092. * Disposes the resources of the material.
  45093. * @param forceDisposeEffect - Forces the disposal of effects.
  45094. * @param forceDisposeTextures - Forces the disposal of all textures.
  45095. */
  45096. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45097. if (forceDisposeTextures) {
  45098. if (this._albedoTexture) {
  45099. this._albedoTexture.dispose();
  45100. }
  45101. if (this._ambientTexture) {
  45102. this._ambientTexture.dispose();
  45103. }
  45104. if (this._opacityTexture) {
  45105. this._opacityTexture.dispose();
  45106. }
  45107. if (this._reflectionTexture) {
  45108. this._reflectionTexture.dispose();
  45109. }
  45110. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45111. this._environmentBRDFTexture.dispose();
  45112. }
  45113. if (this._emissiveTexture) {
  45114. this._emissiveTexture.dispose();
  45115. }
  45116. if (this._metallicTexture) {
  45117. this._metallicTexture.dispose();
  45118. }
  45119. if (this._reflectivityTexture) {
  45120. this._reflectivityTexture.dispose();
  45121. }
  45122. if (this._bumpTexture) {
  45123. this._bumpTexture.dispose();
  45124. }
  45125. if (this._lightmapTexture) {
  45126. this._lightmapTexture.dispose();
  45127. }
  45128. if (this._refractionTexture) {
  45129. this._refractionTexture.dispose();
  45130. }
  45131. }
  45132. this._renderTargets.dispose();
  45133. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45134. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45135. }
  45136. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45137. };
  45138. /**
  45139. * Stores the reflectivity values based on metallic roughness workflow.
  45140. */
  45141. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45142. __decorate([
  45143. BABYLON.serializeAsImageProcessingConfiguration()
  45144. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45145. __decorate([
  45146. BABYLON.serialize()
  45147. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45151. return PBRBaseMaterial;
  45152. }(BABYLON.PushMaterial));
  45153. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45154. })(BABYLON || (BABYLON = {}));
  45155. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45156. var BABYLON;
  45157. (function (BABYLON) {
  45158. /**
  45159. * The Physically based simple base material of BJS.
  45160. *
  45161. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45162. * It is used as the base class for both the specGloss and metalRough conventions.
  45163. */
  45164. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45165. __extends(PBRBaseSimpleMaterial, _super);
  45166. /**
  45167. * Instantiates a new PBRMaterial instance.
  45168. *
  45169. * @param name The material name
  45170. * @param scene The scene the material will be use in.
  45171. */
  45172. function PBRBaseSimpleMaterial(name, scene) {
  45173. var _this = _super.call(this, name, scene) || this;
  45174. /**
  45175. * Number of Simultaneous lights allowed on the material.
  45176. */
  45177. _this.maxSimultaneousLights = 4;
  45178. /**
  45179. * If sets to true, disables all the lights affecting the material.
  45180. */
  45181. _this.disableLighting = false;
  45182. /**
  45183. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45184. */
  45185. _this.invertNormalMapX = false;
  45186. /**
  45187. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45188. */
  45189. _this.invertNormalMapY = false;
  45190. /**
  45191. * Emissivie color used to self-illuminate the model.
  45192. */
  45193. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45194. /**
  45195. * Occlusion Channel Strenght.
  45196. */
  45197. _this.occlusionStrength = 1.0;
  45198. _this.useLightmapAsShadowmap = false;
  45199. _this._useAlphaFromAlbedoTexture = true;
  45200. _this._useAmbientInGrayScale = true;
  45201. return _this;
  45202. }
  45203. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45204. /**
  45205. * Gets the current double sided mode.
  45206. */
  45207. get: function () {
  45208. return this._twoSidedLighting;
  45209. },
  45210. /**
  45211. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45212. */
  45213. set: function (value) {
  45214. if (this._twoSidedLighting === value) {
  45215. return;
  45216. }
  45217. this._twoSidedLighting = value;
  45218. this.backFaceCulling = !value;
  45219. this._markAllSubMeshesAsTexturesDirty();
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. /**
  45225. * Return the active textures of the material.
  45226. */
  45227. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45228. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45229. if (this.environmentTexture) {
  45230. activeTextures.push(this.environmentTexture);
  45231. }
  45232. if (this.normalTexture) {
  45233. activeTextures.push(this.normalTexture);
  45234. }
  45235. if (this.emissiveTexture) {
  45236. activeTextures.push(this.emissiveTexture);
  45237. }
  45238. if (this.occlusionTexture) {
  45239. activeTextures.push(this.occlusionTexture);
  45240. }
  45241. if (this.lightmapTexture) {
  45242. activeTextures.push(this.lightmapTexture);
  45243. }
  45244. return activeTextures;
  45245. };
  45246. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45247. if (_super.prototype.hasTexture.call(this, texture)) {
  45248. return true;
  45249. }
  45250. if (this.lightmapTexture === texture) {
  45251. return true;
  45252. }
  45253. return false;
  45254. };
  45255. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45256. return "PBRBaseSimpleMaterial";
  45257. };
  45258. __decorate([
  45259. BABYLON.serialize(),
  45260. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45261. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45262. __decorate([
  45263. BABYLON.serialize(),
  45264. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45265. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45266. __decorate([
  45267. BABYLON.serializeAsTexture(),
  45268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45269. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45270. __decorate([
  45271. BABYLON.serialize(),
  45272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45273. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45274. __decorate([
  45275. BABYLON.serialize(),
  45276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45277. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45278. __decorate([
  45279. BABYLON.serializeAsTexture(),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45281. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45282. __decorate([
  45283. BABYLON.serializeAsColor3("emissive"),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45286. __decorate([
  45287. BABYLON.serializeAsTexture(),
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45290. __decorate([
  45291. BABYLON.serialize(),
  45292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45293. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45294. __decorate([
  45295. BABYLON.serializeAsTexture(),
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45297. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45298. __decorate([
  45299. BABYLON.serialize(),
  45300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45301. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45302. __decorate([
  45303. BABYLON.serialize()
  45304. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45305. __decorate([
  45306. BABYLON.serializeAsTexture(),
  45307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45308. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45309. __decorate([
  45310. BABYLON.serialize(),
  45311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45312. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45313. return PBRBaseSimpleMaterial;
  45314. }(BABYLON.PBRBaseMaterial));
  45315. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45316. })(BABYLON || (BABYLON = {}));
  45317. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45318. var BABYLON;
  45319. (function (BABYLON) {
  45320. /**
  45321. * The Physically based material of BJS.
  45322. *
  45323. * This offers the main features of a standard PBR material.
  45324. * For more information, please refer to the documentation :
  45325. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45326. */
  45327. var PBRMaterial = /** @class */ (function (_super) {
  45328. __extends(PBRMaterial, _super);
  45329. /**
  45330. * Instantiates a new PBRMaterial instance.
  45331. *
  45332. * @param name The material name
  45333. * @param scene The scene the material will be use in.
  45334. */
  45335. function PBRMaterial(name, scene) {
  45336. var _this = _super.call(this, name, scene) || this;
  45337. /**
  45338. * Intensity of the direct lights e.g. the four lights available in your scene.
  45339. * This impacts both the direct diffuse and specular highlights.
  45340. */
  45341. _this.directIntensity = 1.0;
  45342. /**
  45343. * Intensity of the emissive part of the material.
  45344. * This helps controlling the emissive effect without modifying the emissive color.
  45345. */
  45346. _this.emissiveIntensity = 1.0;
  45347. /**
  45348. * Intensity of the environment e.g. how much the environment will light the object
  45349. * either through harmonics for rough material or through the refelction for shiny ones.
  45350. */
  45351. _this.environmentIntensity = 1.0;
  45352. /**
  45353. * This is a special control allowing the reduction of the specular highlights coming from the
  45354. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45355. */
  45356. _this.specularIntensity = 1.0;
  45357. /**
  45358. * Debug Control allowing disabling the bump map on this material.
  45359. */
  45360. _this.disableBumpMap = false;
  45361. /**
  45362. * AKA Occlusion Texture Intensity in other nomenclature.
  45363. */
  45364. _this.ambientTextureStrength = 1.0;
  45365. /**
  45366. * The color of a material in ambient lighting.
  45367. */
  45368. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45369. /**
  45370. * AKA Diffuse Color in other nomenclature.
  45371. */
  45372. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45373. /**
  45374. * AKA Specular Color in other nomenclature.
  45375. */
  45376. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45377. /**
  45378. * The color reflected from the material.
  45379. */
  45380. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45381. /**
  45382. * The color emitted from the material.
  45383. */
  45384. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45385. /**
  45386. * AKA Glossiness in other nomenclature.
  45387. */
  45388. _this.microSurface = 1.0;
  45389. /**
  45390. * source material index of refraction (IOR)' / 'destination material IOR.
  45391. */
  45392. _this.indexOfRefraction = 0.66;
  45393. /**
  45394. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45395. */
  45396. _this.invertRefractionY = false;
  45397. /**
  45398. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45399. * Materials half opaque for instance using refraction could benefit from this control.
  45400. */
  45401. _this.linkRefractionWithTransparency = false;
  45402. _this.useLightmapAsShadowmap = false;
  45403. /**
  45404. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45405. */
  45406. _this.useAlphaFromAlbedoTexture = false;
  45407. /**
  45408. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45409. */
  45410. _this.forceAlphaTest = false;
  45411. /**
  45412. * Defines the alpha limits in alpha test mode.
  45413. */
  45414. _this.alphaCutOff = 0.4;
  45415. /**
  45416. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45417. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45418. */
  45419. _this.useSpecularOverAlpha = true;
  45420. /**
  45421. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45422. */
  45423. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45424. /**
  45425. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45426. */
  45427. _this.useRoughnessFromMetallicTextureAlpha = true;
  45428. /**
  45429. * Specifies if the metallic texture contains the roughness information in its green channel.
  45430. */
  45431. _this.useRoughnessFromMetallicTextureGreen = false;
  45432. /**
  45433. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45434. */
  45435. _this.useMetallnessFromMetallicTextureBlue = false;
  45436. /**
  45437. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45438. */
  45439. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45440. /**
  45441. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45442. */
  45443. _this.useAmbientInGrayScale = false;
  45444. /**
  45445. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45446. * The material will try to infer what glossiness each pixel should be.
  45447. */
  45448. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45449. /**
  45450. * BJS is using an harcoded light falloff based on a manually sets up range.
  45451. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45452. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45453. */
  45454. _this.usePhysicalLightFalloff = true;
  45455. /**
  45456. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45457. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45458. */
  45459. _this.useRadianceOverAlpha = true;
  45460. /**
  45461. * Allows using an object space normal map (instead of tangent space).
  45462. */
  45463. _this.useObjectSpaceNormalMap = false;
  45464. /**
  45465. * Allows using the bump map in parallax mode.
  45466. */
  45467. _this.useParallax = false;
  45468. /**
  45469. * Allows using the bump map in parallax occlusion mode.
  45470. */
  45471. _this.useParallaxOcclusion = false;
  45472. /**
  45473. * Controls the scale bias of the parallax mode.
  45474. */
  45475. _this.parallaxScaleBias = 0.05;
  45476. /**
  45477. * If sets to true, disables all the lights affecting the material.
  45478. */
  45479. _this.disableLighting = false;
  45480. /**
  45481. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45482. */
  45483. _this.forceIrradianceInFragment = false;
  45484. /**
  45485. * Number of Simultaneous lights allowed on the material.
  45486. */
  45487. _this.maxSimultaneousLights = 4;
  45488. /**
  45489. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45490. */
  45491. _this.invertNormalMapX = false;
  45492. /**
  45493. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45494. */
  45495. _this.invertNormalMapY = false;
  45496. /**
  45497. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45498. */
  45499. _this.twoSidedLighting = false;
  45500. /**
  45501. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45502. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45503. */
  45504. _this.useAlphaFresnel = false;
  45505. /**
  45506. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45507. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45508. */
  45509. _this.useLinearAlphaFresnel = false;
  45510. /**
  45511. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45512. * And/Or occlude the blended part.
  45513. */
  45514. _this.environmentBRDFTexture = null;
  45515. /**
  45516. * Force normal to face away from face.
  45517. */
  45518. _this.forceNormalForward = false;
  45519. /**
  45520. * Enables specular anti aliasing in the PBR shader.
  45521. * It will both interacts on the Geometry for analytical and IBL lighting.
  45522. * It also prefilter the roughness map based on the bump values.
  45523. */
  45524. _this.enableSpecularAntiAliasing = false;
  45525. /**
  45526. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45527. * makes the reflect vector face the model (under horizon).
  45528. */
  45529. _this.useHorizonOcclusion = true;
  45530. /**
  45531. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45532. * too much the area relying on ambient texture to define their ambient occlusion.
  45533. */
  45534. _this.useRadianceOcclusion = true;
  45535. /**
  45536. * If set to true, no lighting calculations will be applied.
  45537. */
  45538. _this.unlit = false;
  45539. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45540. return _this;
  45541. }
  45542. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45543. /**
  45544. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45545. */
  45546. get: function () {
  45547. return this._PBRMATERIAL_OPAQUE;
  45548. },
  45549. enumerable: true,
  45550. configurable: true
  45551. });
  45552. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45553. /**
  45554. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45555. */
  45556. get: function () {
  45557. return this._PBRMATERIAL_ALPHATEST;
  45558. },
  45559. enumerable: true,
  45560. configurable: true
  45561. });
  45562. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45563. /**
  45564. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45565. */
  45566. get: function () {
  45567. return this._PBRMATERIAL_ALPHABLEND;
  45568. },
  45569. enumerable: true,
  45570. configurable: true
  45571. });
  45572. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45573. /**
  45574. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45575. * They are also discarded below the alpha cutoff threshold to improve performances.
  45576. */
  45577. get: function () {
  45578. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45584. /**
  45585. * Gets the image processing configuration used either in this material.
  45586. */
  45587. get: function () {
  45588. return this._imageProcessingConfiguration;
  45589. },
  45590. /**
  45591. * Sets the Default image processing configuration used either in the this material.
  45592. *
  45593. * If sets to null, the scene one is in use.
  45594. */
  45595. set: function (value) {
  45596. this._attachImageProcessingConfiguration(value);
  45597. // Ensure the effect will be rebuilt.
  45598. this._markAllSubMeshesAsTexturesDirty();
  45599. },
  45600. enumerable: true,
  45601. configurable: true
  45602. });
  45603. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45604. /**
  45605. * Gets wether the color curves effect is enabled.
  45606. */
  45607. get: function () {
  45608. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45609. },
  45610. /**
  45611. * Sets wether the color curves effect is enabled.
  45612. */
  45613. set: function (value) {
  45614. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45615. },
  45616. enumerable: true,
  45617. configurable: true
  45618. });
  45619. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45620. /**
  45621. * Gets wether the color grading effect is enabled.
  45622. */
  45623. get: function () {
  45624. return this.imageProcessingConfiguration.colorGradingEnabled;
  45625. },
  45626. /**
  45627. * Gets wether the color grading effect is enabled.
  45628. */
  45629. set: function (value) {
  45630. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45631. },
  45632. enumerable: true,
  45633. configurable: true
  45634. });
  45635. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45636. /**
  45637. * Gets wether tonemapping is enabled or not.
  45638. */
  45639. get: function () {
  45640. return this._imageProcessingConfiguration.toneMappingEnabled;
  45641. },
  45642. /**
  45643. * Sets wether tonemapping is enabled or not
  45644. */
  45645. set: function (value) {
  45646. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45647. },
  45648. enumerable: true,
  45649. configurable: true
  45650. });
  45651. ;
  45652. ;
  45653. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45654. /**
  45655. * The camera exposure used on this material.
  45656. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45657. * This corresponds to a photographic exposure.
  45658. */
  45659. get: function () {
  45660. return this._imageProcessingConfiguration.exposure;
  45661. },
  45662. /**
  45663. * The camera exposure used on this material.
  45664. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45665. * This corresponds to a photographic exposure.
  45666. */
  45667. set: function (value) {
  45668. this._imageProcessingConfiguration.exposure = value;
  45669. },
  45670. enumerable: true,
  45671. configurable: true
  45672. });
  45673. ;
  45674. ;
  45675. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45676. /**
  45677. * Gets The camera contrast used on this material.
  45678. */
  45679. get: function () {
  45680. return this._imageProcessingConfiguration.contrast;
  45681. },
  45682. /**
  45683. * Sets The camera contrast used on this material.
  45684. */
  45685. set: function (value) {
  45686. this._imageProcessingConfiguration.contrast = value;
  45687. },
  45688. enumerable: true,
  45689. configurable: true
  45690. });
  45691. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45692. /**
  45693. * Gets the Color Grading 2D Lookup Texture.
  45694. */
  45695. get: function () {
  45696. return this._imageProcessingConfiguration.colorGradingTexture;
  45697. },
  45698. /**
  45699. * Sets the Color Grading 2D Lookup Texture.
  45700. */
  45701. set: function (value) {
  45702. this._imageProcessingConfiguration.colorGradingTexture = value;
  45703. },
  45704. enumerable: true,
  45705. configurable: true
  45706. });
  45707. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45708. /**
  45709. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45710. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45711. * 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;
  45712. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45713. */
  45714. get: function () {
  45715. return this._imageProcessingConfiguration.colorCurves;
  45716. },
  45717. /**
  45718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45720. * 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;
  45721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45722. */
  45723. set: function (value) {
  45724. this._imageProcessingConfiguration.colorCurves = value;
  45725. },
  45726. enumerable: true,
  45727. configurable: true
  45728. });
  45729. /**
  45730. * Returns the name of this material class.
  45731. */
  45732. PBRMaterial.prototype.getClassName = function () {
  45733. return "PBRMaterial";
  45734. };
  45735. /**
  45736. * Returns an array of the actively used textures.
  45737. * @returns - Array of BaseTextures
  45738. */
  45739. PBRMaterial.prototype.getActiveTextures = function () {
  45740. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45741. if (this._albedoTexture) {
  45742. activeTextures.push(this._albedoTexture);
  45743. }
  45744. if (this._ambientTexture) {
  45745. activeTextures.push(this._ambientTexture);
  45746. }
  45747. if (this._opacityTexture) {
  45748. activeTextures.push(this._opacityTexture);
  45749. }
  45750. if (this._reflectionTexture) {
  45751. activeTextures.push(this._reflectionTexture);
  45752. }
  45753. if (this._emissiveTexture) {
  45754. activeTextures.push(this._emissiveTexture);
  45755. }
  45756. if (this._reflectivityTexture) {
  45757. activeTextures.push(this._reflectivityTexture);
  45758. }
  45759. if (this._metallicTexture) {
  45760. activeTextures.push(this._metallicTexture);
  45761. }
  45762. if (this._microSurfaceTexture) {
  45763. activeTextures.push(this._microSurfaceTexture);
  45764. }
  45765. if (this._bumpTexture) {
  45766. activeTextures.push(this._bumpTexture);
  45767. }
  45768. if (this._lightmapTexture) {
  45769. activeTextures.push(this._lightmapTexture);
  45770. }
  45771. if (this._refractionTexture) {
  45772. activeTextures.push(this._refractionTexture);
  45773. }
  45774. return activeTextures;
  45775. };
  45776. /**
  45777. * Checks to see if a texture is used in the material.
  45778. * @param texture - Base texture to use.
  45779. * @returns - Boolean specifying if a texture is used in the material.
  45780. */
  45781. PBRMaterial.prototype.hasTexture = function (texture) {
  45782. if (_super.prototype.hasTexture.call(this, texture)) {
  45783. return true;
  45784. }
  45785. if (this._albedoTexture === texture) {
  45786. return true;
  45787. }
  45788. if (this._ambientTexture === texture) {
  45789. return true;
  45790. }
  45791. if (this._opacityTexture === texture) {
  45792. return true;
  45793. }
  45794. if (this._reflectionTexture === texture) {
  45795. return true;
  45796. }
  45797. if (this._reflectivityTexture === texture) {
  45798. return true;
  45799. }
  45800. if (this._metallicTexture === texture) {
  45801. return true;
  45802. }
  45803. if (this._microSurfaceTexture === texture) {
  45804. return true;
  45805. }
  45806. if (this._bumpTexture === texture) {
  45807. return true;
  45808. }
  45809. if (this._lightmapTexture === texture) {
  45810. return true;
  45811. }
  45812. if (this._refractionTexture === texture) {
  45813. return true;
  45814. }
  45815. return false;
  45816. };
  45817. /**
  45818. * Makes a duplicate of the current material.
  45819. * @param name - name to use for the new material.
  45820. */
  45821. PBRMaterial.prototype.clone = function (name) {
  45822. var _this = this;
  45823. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45824. clone.id = name;
  45825. clone.name = name;
  45826. return clone;
  45827. };
  45828. /**
  45829. * Serializes this PBR Material.
  45830. * @returns - An object with the serialized material.
  45831. */
  45832. PBRMaterial.prototype.serialize = function () {
  45833. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45834. serializationObject.customType = "BABYLON.PBRMaterial";
  45835. return serializationObject;
  45836. };
  45837. // Statics
  45838. /**
  45839. * Parses a PBR Material from a serialized object.
  45840. * @param source - Serialized object.
  45841. * @param scene - BJS scene instance.
  45842. * @param rootUrl - url for the scene object
  45843. * @returns - PBRMaterial
  45844. */
  45845. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45846. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45847. };
  45848. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45849. /**
  45850. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45851. */
  45852. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45853. /**
  45854. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45855. */
  45856. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45857. /**
  45858. * 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.
  45859. * They are also discarded below the alpha cutoff threshold to improve performances.
  45860. */
  45861. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "directIntensity", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45882. __decorate([
  45883. BABYLON.serializeAsTexture(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45886. __decorate([
  45887. BABYLON.serializeAsTexture(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsTexture(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45897. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsTexture(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45902. __decorate([
  45903. BABYLON.serializeAsTexture(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45906. __decorate([
  45907. BABYLON.serializeAsTexture(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45910. __decorate([
  45911. BABYLON.serializeAsTexture(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "metallic", void 0);
  45918. __decorate([
  45919. BABYLON.serialize(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "roughness", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsTexture(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45926. __decorate([
  45927. BABYLON.serializeAsTexture(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45930. __decorate([
  45931. BABYLON.serializeAsTexture(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45933. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45934. __decorate([
  45935. BABYLON.serializeAsTexture(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsColor3("ambient"),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRMaterial.prototype, "ambientColor", void 0);
  45942. __decorate([
  45943. BABYLON.serializeAsColor3("albedo"),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45945. ], PBRMaterial.prototype, "albedoColor", void 0);
  45946. __decorate([
  45947. BABYLON.serializeAsColor3("reflectivity"),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45949. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45950. __decorate([
  45951. BABYLON.serializeAsColor3("reflection"),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45954. __decorate([
  45955. BABYLON.serializeAsColor3("emissive"),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "microSurface", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45966. __decorate([
  45967. BABYLON.serialize(),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45981. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45985. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45989. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45990. __decorate([
  45991. BABYLON.serialize(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45993. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45994. __decorate([
  45995. BABYLON.serialize(),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45997. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46001. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46005. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46006. __decorate([
  46007. BABYLON.serialize(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46009. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46010. __decorate([
  46011. BABYLON.serialize(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46013. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46014. __decorate([
  46015. BABYLON.serialize(),
  46016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46017. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46018. __decorate([
  46019. BABYLON.serialize(),
  46020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46021. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46022. __decorate([
  46023. BABYLON.serialize(),
  46024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46025. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46026. __decorate([
  46027. BABYLON.serialize(),
  46028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46029. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46030. __decorate([
  46031. BABYLON.serialize(),
  46032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46033. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46034. __decorate([
  46035. BABYLON.serialize(),
  46036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46037. ], PBRMaterial.prototype, "useParallax", void 0);
  46038. __decorate([
  46039. BABYLON.serialize(),
  46040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46041. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46042. __decorate([
  46043. BABYLON.serialize(),
  46044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46045. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46046. __decorate([
  46047. BABYLON.serialize(),
  46048. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46049. ], PBRMaterial.prototype, "disableLighting", void 0);
  46050. __decorate([
  46051. BABYLON.serialize(),
  46052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46053. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46054. __decorate([
  46055. BABYLON.serialize(),
  46056. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46057. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46058. __decorate([
  46059. BABYLON.serialize(),
  46060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46061. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46062. __decorate([
  46063. BABYLON.serialize(),
  46064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46065. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46066. __decorate([
  46067. BABYLON.serialize(),
  46068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46069. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46070. __decorate([
  46071. BABYLON.serialize(),
  46072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46073. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46074. __decorate([
  46075. BABYLON.serialize(),
  46076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46077. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46078. __decorate([
  46079. BABYLON.serializeAsTexture(),
  46080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46081. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46082. __decorate([
  46083. BABYLON.serialize(),
  46084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46085. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46086. __decorate([
  46087. BABYLON.serialize(),
  46088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46089. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46090. __decorate([
  46091. BABYLON.serialize(),
  46092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46093. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46094. __decorate([
  46095. BABYLON.serialize(),
  46096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46097. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46098. __decorate([
  46099. BABYLON.serialize(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46101. ], PBRMaterial.prototype, "unlit", void 0);
  46102. return PBRMaterial;
  46103. }(BABYLON.PBRBaseMaterial));
  46104. BABYLON.PBRMaterial = PBRMaterial;
  46105. })(BABYLON || (BABYLON = {}));
  46106. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46107. var BABYLON;
  46108. (function (BABYLON) {
  46109. /**
  46110. * The PBR material of BJS following the metal roughness convention.
  46111. *
  46112. * This fits to the PBR convention in the GLTF definition:
  46113. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46114. */
  46115. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46116. __extends(PBRMetallicRoughnessMaterial, _super);
  46117. /**
  46118. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46119. *
  46120. * @param name The material name
  46121. * @param scene The scene the material will be use in.
  46122. */
  46123. function PBRMetallicRoughnessMaterial(name, scene) {
  46124. var _this = _super.call(this, name, scene) || this;
  46125. _this._useRoughnessFromMetallicTextureAlpha = false;
  46126. _this._useRoughnessFromMetallicTextureGreen = true;
  46127. _this._useMetallnessFromMetallicTextureBlue = true;
  46128. _this.metallic = 1.0;
  46129. _this.roughness = 1.0;
  46130. return _this;
  46131. }
  46132. /**
  46133. * Return the currrent class name of the material.
  46134. */
  46135. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46136. return "PBRMetallicRoughnessMaterial";
  46137. };
  46138. /**
  46139. * Return the active textures of the material.
  46140. */
  46141. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46142. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46143. if (this.baseTexture) {
  46144. activeTextures.push(this.baseTexture);
  46145. }
  46146. if (this.metallicRoughnessTexture) {
  46147. activeTextures.push(this.metallicRoughnessTexture);
  46148. }
  46149. return activeTextures;
  46150. };
  46151. /**
  46152. * Checks to see if a texture is used in the material.
  46153. * @param texture - Base texture to use.
  46154. * @returns - Boolean specifying if a texture is used in the material.
  46155. */
  46156. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46157. if (_super.prototype.hasTexture.call(this, texture)) {
  46158. return true;
  46159. }
  46160. if (this.baseTexture === texture) {
  46161. return true;
  46162. }
  46163. if (this.metallicRoughnessTexture === texture) {
  46164. return true;
  46165. }
  46166. return false;
  46167. };
  46168. /**
  46169. * Makes a duplicate of the current material.
  46170. * @param name - name to use for the new material.
  46171. */
  46172. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46173. var _this = this;
  46174. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46175. clone.id = name;
  46176. clone.name = name;
  46177. return clone;
  46178. };
  46179. /**
  46180. * Serialize the material to a parsable JSON object.
  46181. */
  46182. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46184. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46185. return serializationObject;
  46186. };
  46187. /**
  46188. * Parses a JSON object correponding to the serialize function.
  46189. */
  46190. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46191. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46192. };
  46193. __decorate([
  46194. BABYLON.serializeAsColor3(),
  46195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46196. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46197. __decorate([
  46198. BABYLON.serializeAsTexture(),
  46199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46200. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46201. __decorate([
  46202. BABYLON.serialize(),
  46203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46204. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46205. __decorate([
  46206. BABYLON.serialize(),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46208. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46209. __decorate([
  46210. BABYLON.serializeAsTexture(),
  46211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46212. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46213. return PBRMetallicRoughnessMaterial;
  46214. }(BABYLON.PBRBaseSimpleMaterial));
  46215. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46216. })(BABYLON || (BABYLON = {}));
  46217. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46218. var BABYLON;
  46219. (function (BABYLON) {
  46220. /**
  46221. * The PBR material of BJS following the specular glossiness convention.
  46222. *
  46223. * This fits to the PBR convention in the GLTF definition:
  46224. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46225. */
  46226. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46227. __extends(PBRSpecularGlossinessMaterial, _super);
  46228. /**
  46229. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46230. *
  46231. * @param name The material name
  46232. * @param scene The scene the material will be use in.
  46233. */
  46234. function PBRSpecularGlossinessMaterial(name, scene) {
  46235. var _this = _super.call(this, name, scene) || this;
  46236. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46237. return _this;
  46238. }
  46239. /**
  46240. * Return the currrent class name of the material.
  46241. */
  46242. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46243. return "PBRSpecularGlossinessMaterial";
  46244. };
  46245. /**
  46246. * Return the active textures of the material.
  46247. */
  46248. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46249. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46250. if (this.diffuseTexture) {
  46251. activeTextures.push(this.diffuseTexture);
  46252. }
  46253. if (this.specularGlossinessTexture) {
  46254. activeTextures.push(this.specularGlossinessTexture);
  46255. }
  46256. return activeTextures;
  46257. };
  46258. /**
  46259. * Checks to see if a texture is used in the material.
  46260. * @param texture - Base texture to use.
  46261. * @returns - Boolean specifying if a texture is used in the material.
  46262. */
  46263. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46264. if (_super.prototype.hasTexture.call(this, texture)) {
  46265. return true;
  46266. }
  46267. if (this.diffuseTexture === texture) {
  46268. return true;
  46269. }
  46270. if (this.specularGlossinessTexture === texture) {
  46271. return true;
  46272. }
  46273. return false;
  46274. };
  46275. /**
  46276. * Makes a duplicate of the current material.
  46277. * @param name - name to use for the new material.
  46278. */
  46279. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46280. var _this = this;
  46281. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46282. clone.id = name;
  46283. clone.name = name;
  46284. return clone;
  46285. };
  46286. /**
  46287. * Serialize the material to a parsable JSON object.
  46288. */
  46289. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46290. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46291. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46292. return serializationObject;
  46293. };
  46294. /**
  46295. * Parses a JSON object correponding to the serialize function.
  46296. */
  46297. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46298. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46299. };
  46300. __decorate([
  46301. BABYLON.serializeAsColor3("diffuse"),
  46302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46303. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46304. __decorate([
  46305. BABYLON.serializeAsTexture(),
  46306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46307. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46308. __decorate([
  46309. BABYLON.serializeAsColor3("specular"),
  46310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46311. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46312. __decorate([
  46313. BABYLON.serialize(),
  46314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46315. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46316. __decorate([
  46317. BABYLON.serializeAsTexture(),
  46318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46319. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46320. return PBRSpecularGlossinessMaterial;
  46321. }(BABYLON.PBRBaseSimpleMaterial));
  46322. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46323. })(BABYLON || (BABYLON = {}));
  46324. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46325. var BABYLON;
  46326. (function (BABYLON) {
  46327. BABYLON.CameraInputTypes = {};
  46328. var CameraInputsManager = /** @class */ (function () {
  46329. function CameraInputsManager(camera) {
  46330. this.attached = {};
  46331. this.camera = camera;
  46332. this.checkInputs = function () { };
  46333. }
  46334. /**
  46335. * Add an input method to a camera.
  46336. * builtin inputs example: camera.inputs.addGamepad();
  46337. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46338. * @param input camera input method
  46339. */
  46340. CameraInputsManager.prototype.add = function (input) {
  46341. var type = input.getSimpleName();
  46342. if (this.attached[type]) {
  46343. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46344. return;
  46345. }
  46346. this.attached[type] = input;
  46347. input.camera = this.camera;
  46348. //for checkInputs, we are dynamically creating a function
  46349. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46350. if (input.checkInputs) {
  46351. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46352. }
  46353. if (this.attachedElement) {
  46354. input.attachControl(this.attachedElement);
  46355. }
  46356. };
  46357. /**
  46358. * Remove a specific input method from a camera
  46359. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46360. * @param inputToRemove camera input method
  46361. */
  46362. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46363. for (var cam in this.attached) {
  46364. var input = this.attached[cam];
  46365. if (input === inputToRemove) {
  46366. input.detachControl(this.attachedElement);
  46367. input.camera = null;
  46368. delete this.attached[cam];
  46369. this.rebuildInputCheck();
  46370. }
  46371. }
  46372. };
  46373. CameraInputsManager.prototype.removeByType = function (inputType) {
  46374. for (var cam in this.attached) {
  46375. var input = this.attached[cam];
  46376. if (input.getClassName() === inputType) {
  46377. input.detachControl(this.attachedElement);
  46378. input.camera = null;
  46379. delete this.attached[cam];
  46380. this.rebuildInputCheck();
  46381. }
  46382. }
  46383. };
  46384. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46385. var current = this.checkInputs;
  46386. return function () {
  46387. current();
  46388. fn();
  46389. };
  46390. };
  46391. CameraInputsManager.prototype.attachInput = function (input) {
  46392. if (this.attachedElement) {
  46393. input.attachControl(this.attachedElement, this.noPreventDefault);
  46394. }
  46395. };
  46396. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46397. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46398. if (this.attachedElement) {
  46399. return;
  46400. }
  46401. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46402. this.attachedElement = element;
  46403. this.noPreventDefault = noPreventDefault;
  46404. for (var cam in this.attached) {
  46405. this.attached[cam].attachControl(element, noPreventDefault);
  46406. }
  46407. };
  46408. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46409. if (disconnect === void 0) { disconnect = false; }
  46410. if (this.attachedElement !== element) {
  46411. return;
  46412. }
  46413. for (var cam in this.attached) {
  46414. this.attached[cam].detachControl(element);
  46415. if (disconnect) {
  46416. this.attached[cam].camera = null;
  46417. }
  46418. }
  46419. this.attachedElement = null;
  46420. };
  46421. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46422. this.checkInputs = function () { };
  46423. for (var cam in this.attached) {
  46424. var input = this.attached[cam];
  46425. if (input.checkInputs) {
  46426. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46427. }
  46428. }
  46429. };
  46430. /**
  46431. * Remove all attached input methods from a camera
  46432. */
  46433. CameraInputsManager.prototype.clear = function () {
  46434. if (this.attachedElement) {
  46435. this.detachElement(this.attachedElement, true);
  46436. }
  46437. this.attached = {};
  46438. this.attachedElement = null;
  46439. this.checkInputs = function () { };
  46440. };
  46441. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46442. var inputs = {};
  46443. for (var cam in this.attached) {
  46444. var input = this.attached[cam];
  46445. var res = BABYLON.SerializationHelper.Serialize(input);
  46446. inputs[input.getClassName()] = res;
  46447. }
  46448. serializedCamera.inputsmgr = inputs;
  46449. };
  46450. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46451. var parsedInputs = parsedCamera.inputsmgr;
  46452. if (parsedInputs) {
  46453. this.clear();
  46454. for (var n in parsedInputs) {
  46455. var construct = BABYLON.CameraInputTypes[n];
  46456. if (construct) {
  46457. var parsedinput = parsedInputs[n];
  46458. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46459. this.add(input);
  46460. }
  46461. }
  46462. }
  46463. else {
  46464. //2016-03-08 this part is for managing backward compatibility
  46465. for (var n in this.attached) {
  46466. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46467. if (construct) {
  46468. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46469. this.remove(this.attached[n]);
  46470. this.add(input);
  46471. }
  46472. }
  46473. }
  46474. };
  46475. return CameraInputsManager;
  46476. }());
  46477. BABYLON.CameraInputsManager = CameraInputsManager;
  46478. })(BABYLON || (BABYLON = {}));
  46479. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46480. var BABYLON;
  46481. (function (BABYLON) {
  46482. var TargetCamera = /** @class */ (function (_super) {
  46483. __extends(TargetCamera, _super);
  46484. function TargetCamera(name, position, scene) {
  46485. var _this = _super.call(this, name, position, scene) || this;
  46486. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46487. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46488. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46489. _this.speed = 2.0;
  46490. _this.noRotationConstraint = false;
  46491. _this.lockedTarget = null;
  46492. _this._currentTarget = BABYLON.Vector3.Zero();
  46493. _this._viewMatrix = BABYLON.Matrix.Zero();
  46494. _this._camMatrix = BABYLON.Matrix.Zero();
  46495. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46496. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46497. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46498. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46499. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46500. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46501. _this._tempMatrix = BABYLON.Matrix.Zero();
  46502. return _this;
  46503. }
  46504. TargetCamera.prototype.getFrontPosition = function (distance) {
  46505. this.getWorldMatrix();
  46506. var direction = this.getTarget().subtract(this.position);
  46507. direction.normalize();
  46508. direction.scaleInPlace(distance);
  46509. return this.globalPosition.add(direction);
  46510. };
  46511. TargetCamera.prototype._getLockedTargetPosition = function () {
  46512. if (!this.lockedTarget) {
  46513. return null;
  46514. }
  46515. if (this.lockedTarget.absolutePosition) {
  46516. this.lockedTarget.computeWorldMatrix();
  46517. }
  46518. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46519. };
  46520. TargetCamera.prototype.storeState = function () {
  46521. this._storedPosition = this.position.clone();
  46522. this._storedRotation = this.rotation.clone();
  46523. if (this.rotationQuaternion) {
  46524. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46525. }
  46526. return _super.prototype.storeState.call(this);
  46527. };
  46528. /**
  46529. * Restored camera state. You must call storeState() first
  46530. */
  46531. TargetCamera.prototype._restoreStateValues = function () {
  46532. if (!_super.prototype._restoreStateValues.call(this)) {
  46533. return false;
  46534. }
  46535. this.position = this._storedPosition.clone();
  46536. this.rotation = this._storedRotation.clone();
  46537. if (this.rotationQuaternion) {
  46538. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46539. }
  46540. this.cameraDirection.copyFromFloats(0, 0, 0);
  46541. this.cameraRotation.copyFromFloats(0, 0);
  46542. return true;
  46543. };
  46544. // Cache
  46545. TargetCamera.prototype._initCache = function () {
  46546. _super.prototype._initCache.call(this);
  46547. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46548. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46549. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46550. };
  46551. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46552. if (!ignoreParentClass) {
  46553. _super.prototype._updateCache.call(this);
  46554. }
  46555. var lockedTargetPosition = this._getLockedTargetPosition();
  46556. if (!lockedTargetPosition) {
  46557. this._cache.lockedTarget = null;
  46558. }
  46559. else {
  46560. if (!this._cache.lockedTarget) {
  46561. this._cache.lockedTarget = lockedTargetPosition.clone();
  46562. }
  46563. else {
  46564. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46565. }
  46566. }
  46567. this._cache.rotation.copyFrom(this.rotation);
  46568. if (this.rotationQuaternion)
  46569. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46570. };
  46571. // Synchronized
  46572. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46573. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46574. return false;
  46575. }
  46576. var lockedTargetPosition = this._getLockedTargetPosition();
  46577. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46578. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46579. };
  46580. // Methods
  46581. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46582. var engine = this.getEngine();
  46583. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46584. };
  46585. // Target
  46586. TargetCamera.prototype.setTarget = function (target) {
  46587. this.upVector.normalize();
  46588. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46589. this._camMatrix.invert();
  46590. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46591. var vDir = target.subtract(this.position);
  46592. if (vDir.x >= 0.0) {
  46593. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46594. }
  46595. else {
  46596. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46597. }
  46598. this.rotation.z = 0;
  46599. if (isNaN(this.rotation.x)) {
  46600. this.rotation.x = 0;
  46601. }
  46602. if (isNaN(this.rotation.y)) {
  46603. this.rotation.y = 0;
  46604. }
  46605. if (isNaN(this.rotation.z)) {
  46606. this.rotation.z = 0;
  46607. }
  46608. if (this.rotationQuaternion) {
  46609. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46610. }
  46611. };
  46612. /**
  46613. * Return the current target position of the camera. This value is expressed in local space.
  46614. */
  46615. TargetCamera.prototype.getTarget = function () {
  46616. return this._currentTarget;
  46617. };
  46618. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46619. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46620. };
  46621. TargetCamera.prototype._updatePosition = function () {
  46622. if (this.parent) {
  46623. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46624. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46625. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46626. return;
  46627. }
  46628. this.position.addInPlace(this.cameraDirection);
  46629. };
  46630. TargetCamera.prototype._checkInputs = function () {
  46631. var needToMove = this._decideIfNeedsToMove();
  46632. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46633. // Move
  46634. if (needToMove) {
  46635. this._updatePosition();
  46636. }
  46637. // Rotate
  46638. if (needToRotate) {
  46639. this.rotation.x += this.cameraRotation.x;
  46640. this.rotation.y += this.cameraRotation.y;
  46641. //rotate, if quaternion is set and rotation was used
  46642. if (this.rotationQuaternion) {
  46643. var len = this.rotation.lengthSquared();
  46644. if (len) {
  46645. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46646. }
  46647. }
  46648. if (!this.noRotationConstraint) {
  46649. var limit = (Math.PI / 2) * 0.95;
  46650. if (this.rotation.x > limit)
  46651. this.rotation.x = limit;
  46652. if (this.rotation.x < -limit)
  46653. this.rotation.x = -limit;
  46654. }
  46655. }
  46656. // Inertia
  46657. if (needToMove) {
  46658. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46659. this.cameraDirection.x = 0;
  46660. }
  46661. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46662. this.cameraDirection.y = 0;
  46663. }
  46664. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46665. this.cameraDirection.z = 0;
  46666. }
  46667. this.cameraDirection.scaleInPlace(this.inertia);
  46668. }
  46669. if (needToRotate) {
  46670. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46671. this.cameraRotation.x = 0;
  46672. }
  46673. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46674. this.cameraRotation.y = 0;
  46675. }
  46676. this.cameraRotation.scaleInPlace(this.inertia);
  46677. }
  46678. _super.prototype._checkInputs.call(this);
  46679. };
  46680. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46681. if (this.rotationQuaternion) {
  46682. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46683. }
  46684. else {
  46685. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46686. }
  46687. //update the up vector!
  46688. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46689. };
  46690. TargetCamera.prototype._getViewMatrix = function () {
  46691. if (this.lockedTarget) {
  46692. this.setTarget(this._getLockedTargetPosition());
  46693. }
  46694. // Compute
  46695. this._updateCameraRotationMatrix();
  46696. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46697. // Computing target and final matrix
  46698. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46699. if (this.getScene().useRightHandedSystem) {
  46700. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46701. }
  46702. else {
  46703. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46704. }
  46705. return this._viewMatrix;
  46706. };
  46707. /**
  46708. * @override
  46709. * Override Camera.createRigCamera
  46710. */
  46711. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46712. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46713. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46714. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46715. if (!this.rotationQuaternion) {
  46716. this.rotationQuaternion = new BABYLON.Quaternion();
  46717. }
  46718. rigCamera._cameraRigParams = {};
  46719. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46720. }
  46721. return rigCamera;
  46722. }
  46723. return null;
  46724. };
  46725. /**
  46726. * @override
  46727. * Override Camera._updateRigCameras
  46728. */
  46729. TargetCamera.prototype._updateRigCameras = function () {
  46730. var camLeft = this._rigCameras[0];
  46731. var camRight = this._rigCameras[1];
  46732. switch (this.cameraRigMode) {
  46733. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46734. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46735. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46737. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46738. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46739. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46740. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46741. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46742. camLeft.setTarget(this.getTarget());
  46743. camRight.setTarget(this.getTarget());
  46744. break;
  46745. case BABYLON.Camera.RIG_MODE_VR:
  46746. if (camLeft.rotationQuaternion) {
  46747. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46748. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46749. }
  46750. else {
  46751. camLeft.rotation.copyFrom(this.rotation);
  46752. camRight.rotation.copyFrom(this.rotation);
  46753. }
  46754. camLeft.position.copyFrom(this.position);
  46755. camRight.position.copyFrom(this.position);
  46756. break;
  46757. }
  46758. _super.prototype._updateRigCameras.call(this);
  46759. };
  46760. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46761. if (!this._rigCamTransformMatrix) {
  46762. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46763. }
  46764. var target = this.getTarget();
  46765. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46766. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46767. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46768. };
  46769. TargetCamera.prototype.getClassName = function () {
  46770. return "TargetCamera";
  46771. };
  46772. __decorate([
  46773. BABYLON.serializeAsVector3()
  46774. ], TargetCamera.prototype, "rotation", void 0);
  46775. __decorate([
  46776. BABYLON.serialize()
  46777. ], TargetCamera.prototype, "speed", void 0);
  46778. __decorate([
  46779. BABYLON.serializeAsMeshReference("lockedTargetId")
  46780. ], TargetCamera.prototype, "lockedTarget", void 0);
  46781. return TargetCamera;
  46782. }(BABYLON.Camera));
  46783. BABYLON.TargetCamera = TargetCamera;
  46784. })(BABYLON || (BABYLON = {}));
  46785. //# sourceMappingURL=babylon.targetCamera.js.map
  46786. var BABYLON;
  46787. (function (BABYLON) {
  46788. var FreeCameraMouseInput = /** @class */ (function () {
  46789. function FreeCameraMouseInput(touchEnabled) {
  46790. if (touchEnabled === void 0) { touchEnabled = true; }
  46791. this.touchEnabled = touchEnabled;
  46792. this.buttons = [0, 1, 2];
  46793. this.angularSensibility = 2000.0;
  46794. this.previousPosition = null;
  46795. }
  46796. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46797. var _this = this;
  46798. var engine = this.camera.getEngine();
  46799. if (!this._pointerInput) {
  46800. this._pointerInput = function (p, s) {
  46801. var evt = p.event;
  46802. if (engine.isInVRExclusivePointerMode) {
  46803. return;
  46804. }
  46805. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46806. return;
  46807. }
  46808. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46809. return;
  46810. }
  46811. var srcElement = (evt.srcElement || evt.target);
  46812. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46813. try {
  46814. srcElement.setPointerCapture(evt.pointerId);
  46815. }
  46816. catch (e) {
  46817. //Nothing to do with the error. Execution will continue.
  46818. }
  46819. _this.previousPosition = {
  46820. x: evt.clientX,
  46821. y: evt.clientY
  46822. };
  46823. if (!noPreventDefault) {
  46824. evt.preventDefault();
  46825. element.focus();
  46826. }
  46827. }
  46828. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46829. try {
  46830. srcElement.releasePointerCapture(evt.pointerId);
  46831. }
  46832. catch (e) {
  46833. //Nothing to do with the error.
  46834. }
  46835. _this.previousPosition = null;
  46836. if (!noPreventDefault) {
  46837. evt.preventDefault();
  46838. }
  46839. }
  46840. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46841. if (!_this.previousPosition || engine.isPointerLock) {
  46842. return;
  46843. }
  46844. var offsetX = evt.clientX - _this.previousPosition.x;
  46845. var offsetY = evt.clientY - _this.previousPosition.y;
  46846. if (_this.camera.getScene().useRightHandedSystem) {
  46847. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46848. }
  46849. else {
  46850. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46851. }
  46852. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46853. _this.previousPosition = {
  46854. x: evt.clientX,
  46855. y: evt.clientY
  46856. };
  46857. if (!noPreventDefault) {
  46858. evt.preventDefault();
  46859. }
  46860. }
  46861. };
  46862. }
  46863. this._onMouseMove = function (evt) {
  46864. if (!engine.isPointerLock) {
  46865. return;
  46866. }
  46867. if (engine.isInVRExclusivePointerMode) {
  46868. return;
  46869. }
  46870. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46871. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46872. if (_this.camera.getScene().useRightHandedSystem) {
  46873. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46874. }
  46875. else {
  46876. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46877. }
  46878. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46879. _this.previousPosition = null;
  46880. if (!noPreventDefault) {
  46881. evt.preventDefault();
  46882. }
  46883. };
  46884. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46885. element.addEventListener("mousemove", this._onMouseMove, false);
  46886. };
  46887. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46888. if (this._observer && element) {
  46889. this.camera.getScene().onPointerObservable.remove(this._observer);
  46890. if (this._onMouseMove) {
  46891. element.removeEventListener("mousemove", this._onMouseMove);
  46892. }
  46893. this._observer = null;
  46894. this._onMouseMove = null;
  46895. this.previousPosition = null;
  46896. }
  46897. };
  46898. FreeCameraMouseInput.prototype.getClassName = function () {
  46899. return "FreeCameraMouseInput";
  46900. };
  46901. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46902. return "mouse";
  46903. };
  46904. __decorate([
  46905. BABYLON.serialize()
  46906. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46907. __decorate([
  46908. BABYLON.serialize()
  46909. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46910. return FreeCameraMouseInput;
  46911. }());
  46912. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46913. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46914. })(BABYLON || (BABYLON = {}));
  46915. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46916. var BABYLON;
  46917. (function (BABYLON) {
  46918. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46919. function FreeCameraKeyboardMoveInput() {
  46920. this._keys = new Array();
  46921. this.keysUp = [38];
  46922. this.keysDown = [40];
  46923. this.keysLeft = [37];
  46924. this.keysRight = [39];
  46925. }
  46926. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46927. var _this = this;
  46928. if (this._onCanvasBlurObserver) {
  46929. return;
  46930. }
  46931. this._scene = this.camera.getScene();
  46932. this._engine = this._scene.getEngine();
  46933. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46934. _this._keys = [];
  46935. });
  46936. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46937. var evt = info.event;
  46938. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46939. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46940. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46941. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46942. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46943. var index = _this._keys.indexOf(evt.keyCode);
  46944. if (index === -1) {
  46945. _this._keys.push(evt.keyCode);
  46946. }
  46947. if (!noPreventDefault) {
  46948. evt.preventDefault();
  46949. }
  46950. }
  46951. }
  46952. else {
  46953. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46954. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46955. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46956. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46957. var index = _this._keys.indexOf(evt.keyCode);
  46958. if (index >= 0) {
  46959. _this._keys.splice(index, 1);
  46960. }
  46961. if (!noPreventDefault) {
  46962. evt.preventDefault();
  46963. }
  46964. }
  46965. }
  46966. });
  46967. };
  46968. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46969. if (this._scene) {
  46970. if (this._onKeyboardObserver) {
  46971. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46972. }
  46973. if (this._onCanvasBlurObserver) {
  46974. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46975. }
  46976. this._onKeyboardObserver = null;
  46977. this._onCanvasBlurObserver = null;
  46978. }
  46979. this._keys = [];
  46980. };
  46981. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46982. if (this._onKeyboardObserver) {
  46983. var camera = this.camera;
  46984. // Keyboard
  46985. for (var index = 0; index < this._keys.length; index++) {
  46986. var keyCode = this._keys[index];
  46987. var speed = camera._computeLocalCameraSpeed();
  46988. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46989. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46990. }
  46991. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46992. camera._localDirection.copyFromFloats(0, 0, speed);
  46993. }
  46994. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46995. camera._localDirection.copyFromFloats(speed, 0, 0);
  46996. }
  46997. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46998. camera._localDirection.copyFromFloats(0, 0, -speed);
  46999. }
  47000. if (camera.getScene().useRightHandedSystem) {
  47001. camera._localDirection.z *= -1;
  47002. }
  47003. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47004. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47005. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47006. }
  47007. }
  47008. };
  47009. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47010. return "FreeCameraKeyboardMoveInput";
  47011. };
  47012. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47013. this._keys = [];
  47014. };
  47015. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47016. return "keyboard";
  47017. };
  47018. __decorate([
  47019. BABYLON.serialize()
  47020. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47021. __decorate([
  47022. BABYLON.serialize()
  47023. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47024. __decorate([
  47025. BABYLON.serialize()
  47026. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47027. __decorate([
  47028. BABYLON.serialize()
  47029. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47030. return FreeCameraKeyboardMoveInput;
  47031. }());
  47032. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47033. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47034. })(BABYLON || (BABYLON = {}));
  47035. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47036. var BABYLON;
  47037. (function (BABYLON) {
  47038. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47039. __extends(FreeCameraInputsManager, _super);
  47040. function FreeCameraInputsManager(camera) {
  47041. return _super.call(this, camera) || this;
  47042. }
  47043. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47044. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47045. return this;
  47046. };
  47047. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47048. if (touchEnabled === void 0) { touchEnabled = true; }
  47049. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47050. return this;
  47051. };
  47052. FreeCameraInputsManager.prototype.addGamepad = function () {
  47053. this.add(new BABYLON.FreeCameraGamepadInput());
  47054. return this;
  47055. };
  47056. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47057. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47058. return this;
  47059. };
  47060. FreeCameraInputsManager.prototype.addTouch = function () {
  47061. this.add(new BABYLON.FreeCameraTouchInput());
  47062. return this;
  47063. };
  47064. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47065. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47066. return this;
  47067. };
  47068. return FreeCameraInputsManager;
  47069. }(BABYLON.CameraInputsManager));
  47070. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47071. })(BABYLON || (BABYLON = {}));
  47072. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47073. var BABYLON;
  47074. (function (BABYLON) {
  47075. var FreeCamera = /** @class */ (function (_super) {
  47076. __extends(FreeCamera, _super);
  47077. function FreeCamera(name, position, scene) {
  47078. var _this = _super.call(this, name, position, scene) || this;
  47079. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47080. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47081. _this.checkCollisions = false;
  47082. _this.applyGravity = false;
  47083. _this._needMoveForGravity = false;
  47084. _this._oldPosition = BABYLON.Vector3.Zero();
  47085. _this._diffPosition = BABYLON.Vector3.Zero();
  47086. _this._newPosition = BABYLON.Vector3.Zero();
  47087. // Collisions
  47088. _this._collisionMask = -1;
  47089. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47090. if (collidedMesh === void 0) { collidedMesh = null; }
  47091. //TODO move this to the collision coordinator!
  47092. if (_this.getScene().workerCollisions)
  47093. newPosition.multiplyInPlace(_this._collider._radius);
  47094. var updatePosition = function (newPos) {
  47095. _this._newPosition.copyFrom(newPos);
  47096. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47097. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47098. _this.position.addInPlace(_this._diffPosition);
  47099. if (_this.onCollide && collidedMesh) {
  47100. _this.onCollide(collidedMesh);
  47101. }
  47102. }
  47103. };
  47104. updatePosition(newPosition);
  47105. };
  47106. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47107. _this.inputs.addKeyboard().addMouse();
  47108. return _this;
  47109. }
  47110. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47111. //-- begin properties for backward compatibility for inputs
  47112. /**
  47113. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47114. * Higher values reduce sensitivity.
  47115. */
  47116. get: function () {
  47117. var mouse = this.inputs.attached["mouse"];
  47118. if (mouse)
  47119. return mouse.angularSensibility;
  47120. return 0;
  47121. },
  47122. /**
  47123. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47124. * Higher values reduce sensitivity.
  47125. */
  47126. set: function (value) {
  47127. var mouse = this.inputs.attached["mouse"];
  47128. if (mouse)
  47129. mouse.angularSensibility = value;
  47130. },
  47131. enumerable: true,
  47132. configurable: true
  47133. });
  47134. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47135. get: function () {
  47136. var keyboard = this.inputs.attached["keyboard"];
  47137. if (keyboard)
  47138. return keyboard.keysUp;
  47139. return [];
  47140. },
  47141. set: function (value) {
  47142. var keyboard = this.inputs.attached["keyboard"];
  47143. if (keyboard)
  47144. keyboard.keysUp = value;
  47145. },
  47146. enumerable: true,
  47147. configurable: true
  47148. });
  47149. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47150. get: function () {
  47151. var keyboard = this.inputs.attached["keyboard"];
  47152. if (keyboard)
  47153. return keyboard.keysDown;
  47154. return [];
  47155. },
  47156. set: function (value) {
  47157. var keyboard = this.inputs.attached["keyboard"];
  47158. if (keyboard)
  47159. keyboard.keysDown = value;
  47160. },
  47161. enumerable: true,
  47162. configurable: true
  47163. });
  47164. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47165. get: function () {
  47166. var keyboard = this.inputs.attached["keyboard"];
  47167. if (keyboard)
  47168. return keyboard.keysLeft;
  47169. return [];
  47170. },
  47171. set: function (value) {
  47172. var keyboard = this.inputs.attached["keyboard"];
  47173. if (keyboard)
  47174. keyboard.keysLeft = value;
  47175. },
  47176. enumerable: true,
  47177. configurable: true
  47178. });
  47179. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47180. get: function () {
  47181. var keyboard = this.inputs.attached["keyboard"];
  47182. if (keyboard)
  47183. return keyboard.keysRight;
  47184. return [];
  47185. },
  47186. set: function (value) {
  47187. var keyboard = this.inputs.attached["keyboard"];
  47188. if (keyboard)
  47189. keyboard.keysRight = value;
  47190. },
  47191. enumerable: true,
  47192. configurable: true
  47193. });
  47194. // Controls
  47195. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47196. this.inputs.attachElement(element, noPreventDefault);
  47197. };
  47198. FreeCamera.prototype.detachControl = function (element) {
  47199. this.inputs.detachElement(element);
  47200. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47201. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47202. };
  47203. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47204. get: function () {
  47205. return this._collisionMask;
  47206. },
  47207. set: function (mask) {
  47208. this._collisionMask = !isNaN(mask) ? mask : -1;
  47209. },
  47210. enumerable: true,
  47211. configurable: true
  47212. });
  47213. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47214. var globalPosition;
  47215. if (this.parent) {
  47216. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47217. }
  47218. else {
  47219. globalPosition = this.position;
  47220. }
  47221. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47222. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47223. if (!this._collider) {
  47224. this._collider = new BABYLON.Collider();
  47225. }
  47226. this._collider._radius = this.ellipsoid;
  47227. this._collider.collisionMask = this._collisionMask;
  47228. //no need for clone, as long as gravity is not on.
  47229. var actualDisplacement = displacement;
  47230. //add gravity to the direction to prevent the dual-collision checking
  47231. if (this.applyGravity) {
  47232. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47233. actualDisplacement = displacement.add(this.getScene().gravity);
  47234. }
  47235. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47236. };
  47237. FreeCamera.prototype._checkInputs = function () {
  47238. if (!this._localDirection) {
  47239. this._localDirection = BABYLON.Vector3.Zero();
  47240. this._transformedDirection = BABYLON.Vector3.Zero();
  47241. }
  47242. this.inputs.checkInputs();
  47243. _super.prototype._checkInputs.call(this);
  47244. };
  47245. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47246. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47247. };
  47248. FreeCamera.prototype._updatePosition = function () {
  47249. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47250. this._collideWithWorld(this.cameraDirection);
  47251. }
  47252. else {
  47253. _super.prototype._updatePosition.call(this);
  47254. }
  47255. };
  47256. FreeCamera.prototype.dispose = function () {
  47257. this.inputs.clear();
  47258. _super.prototype.dispose.call(this);
  47259. };
  47260. FreeCamera.prototype.getClassName = function () {
  47261. return "FreeCamera";
  47262. };
  47263. __decorate([
  47264. BABYLON.serializeAsVector3()
  47265. ], FreeCamera.prototype, "ellipsoid", void 0);
  47266. __decorate([
  47267. BABYLON.serializeAsVector3()
  47268. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47269. __decorate([
  47270. BABYLON.serialize()
  47271. ], FreeCamera.prototype, "checkCollisions", void 0);
  47272. __decorate([
  47273. BABYLON.serialize()
  47274. ], FreeCamera.prototype, "applyGravity", void 0);
  47275. return FreeCamera;
  47276. }(BABYLON.TargetCamera));
  47277. BABYLON.FreeCamera = FreeCamera;
  47278. })(BABYLON || (BABYLON = {}));
  47279. //# sourceMappingURL=babylon.freeCamera.js.map
  47280. var BABYLON;
  47281. (function (BABYLON) {
  47282. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47283. function ArcRotateCameraKeyboardMoveInput() {
  47284. this._keys = new Array();
  47285. this.keysUp = [38];
  47286. this.keysDown = [40];
  47287. this.keysLeft = [37];
  47288. this.keysRight = [39];
  47289. this.keysReset = [220];
  47290. this.panningSensibility = 50.0;
  47291. this.zoomingSensibility = 25.0;
  47292. this.useAltToZoom = true;
  47293. }
  47294. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47295. var _this = this;
  47296. if (this._onCanvasBlurObserver) {
  47297. return;
  47298. }
  47299. this._scene = this.camera.getScene();
  47300. this._engine = this._scene.getEngine();
  47301. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47302. _this._keys = [];
  47303. });
  47304. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47305. var evt = info.event;
  47306. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47307. _this._ctrlPressed = evt.ctrlKey;
  47308. _this._altPressed = evt.altKey;
  47309. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47310. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47311. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47312. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47314. var index = _this._keys.indexOf(evt.keyCode);
  47315. if (index === -1) {
  47316. _this._keys.push(evt.keyCode);
  47317. }
  47318. if (evt.preventDefault) {
  47319. if (!noPreventDefault) {
  47320. evt.preventDefault();
  47321. }
  47322. }
  47323. }
  47324. }
  47325. else {
  47326. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47327. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47328. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47329. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47330. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47331. var index = _this._keys.indexOf(evt.keyCode);
  47332. if (index >= 0) {
  47333. _this._keys.splice(index, 1);
  47334. }
  47335. if (evt.preventDefault) {
  47336. if (!noPreventDefault) {
  47337. evt.preventDefault();
  47338. }
  47339. }
  47340. }
  47341. }
  47342. });
  47343. };
  47344. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47345. if (this._scene) {
  47346. if (this._onKeyboardObserver) {
  47347. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47348. }
  47349. if (this._onCanvasBlurObserver) {
  47350. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47351. }
  47352. this._onKeyboardObserver = null;
  47353. this._onCanvasBlurObserver = null;
  47354. }
  47355. this._keys = [];
  47356. };
  47357. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47358. if (this._onKeyboardObserver) {
  47359. var camera = this.camera;
  47360. for (var index = 0; index < this._keys.length; index++) {
  47361. var keyCode = this._keys[index];
  47362. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47363. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47364. camera.inertialPanningX -= 1 / this.panningSensibility;
  47365. }
  47366. else {
  47367. camera.inertialAlphaOffset -= 0.01;
  47368. }
  47369. }
  47370. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47371. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47372. camera.inertialPanningY += 1 / this.panningSensibility;
  47373. }
  47374. else if (this._altPressed && this.useAltToZoom) {
  47375. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47376. }
  47377. else {
  47378. camera.inertialBetaOffset -= 0.01;
  47379. }
  47380. }
  47381. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47382. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47383. camera.inertialPanningX += 1 / this.panningSensibility;
  47384. }
  47385. else {
  47386. camera.inertialAlphaOffset += 0.01;
  47387. }
  47388. }
  47389. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47390. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47391. camera.inertialPanningY -= 1 / this.panningSensibility;
  47392. }
  47393. else if (this._altPressed && this.useAltToZoom) {
  47394. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47395. }
  47396. else {
  47397. camera.inertialBetaOffset += 0.01;
  47398. }
  47399. }
  47400. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47401. camera.restoreState();
  47402. }
  47403. }
  47404. }
  47405. };
  47406. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47407. return "ArcRotateCameraKeyboardMoveInput";
  47408. };
  47409. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47410. return "keyboard";
  47411. };
  47412. __decorate([
  47413. BABYLON.serialize()
  47414. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47415. __decorate([
  47416. BABYLON.serialize()
  47417. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47418. __decorate([
  47419. BABYLON.serialize()
  47420. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47421. __decorate([
  47422. BABYLON.serialize()
  47423. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47424. __decorate([
  47425. BABYLON.serialize()
  47426. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47427. __decorate([
  47428. BABYLON.serialize()
  47429. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47430. __decorate([
  47431. BABYLON.serialize()
  47432. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47433. __decorate([
  47434. BABYLON.serialize()
  47435. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47436. return ArcRotateCameraKeyboardMoveInput;
  47437. }());
  47438. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47439. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47440. })(BABYLON || (BABYLON = {}));
  47441. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47442. var BABYLON;
  47443. (function (BABYLON) {
  47444. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47445. function ArcRotateCameraMouseWheelInput() {
  47446. this.wheelPrecision = 3.0;
  47447. /**
  47448. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47449. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47450. */
  47451. this.wheelDeltaPercentage = 0;
  47452. }
  47453. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47454. var _this = this;
  47455. this._wheel = function (p, s) {
  47456. //sanity check - this should be a PointerWheel event.
  47457. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47458. return;
  47459. var event = p.event;
  47460. var delta = 0;
  47461. if (event.wheelDelta) {
  47462. if (_this.wheelDeltaPercentage) {
  47463. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47464. if (event.wheelDelta > 0) {
  47465. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47466. }
  47467. else {
  47468. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47469. }
  47470. }
  47471. else {
  47472. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47473. }
  47474. }
  47475. else if (event.detail) {
  47476. delta = -event.detail / _this.wheelPrecision;
  47477. }
  47478. if (delta)
  47479. _this.camera.inertialRadiusOffset += delta;
  47480. if (event.preventDefault) {
  47481. if (!noPreventDefault) {
  47482. event.preventDefault();
  47483. }
  47484. }
  47485. };
  47486. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47487. };
  47488. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47489. if (this._observer && element) {
  47490. this.camera.getScene().onPointerObservable.remove(this._observer);
  47491. this._observer = null;
  47492. this._wheel = null;
  47493. }
  47494. };
  47495. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47496. return "ArcRotateCameraMouseWheelInput";
  47497. };
  47498. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47499. return "mousewheel";
  47500. };
  47501. __decorate([
  47502. BABYLON.serialize()
  47503. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47504. __decorate([
  47505. BABYLON.serialize()
  47506. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47507. return ArcRotateCameraMouseWheelInput;
  47508. }());
  47509. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47510. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47511. })(BABYLON || (BABYLON = {}));
  47512. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47513. var BABYLON;
  47514. (function (BABYLON) {
  47515. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47516. function ArcRotateCameraPointersInput() {
  47517. this.buttons = [0, 1, 2];
  47518. this.angularSensibilityX = 1000.0;
  47519. this.angularSensibilityY = 1000.0;
  47520. this.pinchPrecision = 12.0;
  47521. /**
  47522. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47523. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47524. */
  47525. this.pinchDeltaPercentage = 0;
  47526. this.panningSensibility = 1000.0;
  47527. this.multiTouchPanning = true;
  47528. this.multiTouchPanAndZoom = true;
  47529. this._isPanClick = false;
  47530. this.pinchInwards = true;
  47531. }
  47532. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47533. var _this = this;
  47534. var engine = this.camera.getEngine();
  47535. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47536. var pointA = null;
  47537. var pointB = null;
  47538. var previousPinchSquaredDistance = 0;
  47539. var initialDistance = 0;
  47540. var twoFingerActivityCount = 0;
  47541. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47542. this._pointerInput = function (p, s) {
  47543. var evt = p.event;
  47544. var isTouch = p.event.pointerType === "touch";
  47545. if (engine.isInVRExclusivePointerMode) {
  47546. return;
  47547. }
  47548. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47549. return;
  47550. }
  47551. var srcElement = (evt.srcElement || evt.target);
  47552. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47553. try {
  47554. srcElement.setPointerCapture(evt.pointerId);
  47555. }
  47556. catch (e) {
  47557. //Nothing to do with the error. Execution will continue.
  47558. }
  47559. // Manage panning with pan button click
  47560. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47561. // manage pointers
  47562. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47563. if (pointA === null) {
  47564. pointA = cacheSoloPointer;
  47565. }
  47566. else if (pointB === null) {
  47567. pointB = cacheSoloPointer;
  47568. }
  47569. if (!noPreventDefault) {
  47570. evt.preventDefault();
  47571. element.focus();
  47572. }
  47573. }
  47574. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47575. _this.camera.restoreState();
  47576. }
  47577. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47578. try {
  47579. srcElement.releasePointerCapture(evt.pointerId);
  47580. }
  47581. catch (e) {
  47582. //Nothing to do with the error.
  47583. }
  47584. cacheSoloPointer = null;
  47585. previousPinchSquaredDistance = 0;
  47586. previousMultiTouchPanPosition.isPaning = false;
  47587. previousMultiTouchPanPosition.isPinching = false;
  47588. twoFingerActivityCount = 0;
  47589. initialDistance = 0;
  47590. if (!isTouch) {
  47591. pointB = null; // Mouse and pen are mono pointer
  47592. }
  47593. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47594. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47595. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47596. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47597. if (engine._badOS) {
  47598. pointA = pointB = null;
  47599. }
  47600. else {
  47601. //only remove the impacted pointer in case of multitouch allowing on most
  47602. //platforms switching from rotate to zoom and pan seamlessly.
  47603. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47604. pointA = pointB;
  47605. pointB = null;
  47606. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47607. }
  47608. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47609. pointB = null;
  47610. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47611. }
  47612. else {
  47613. pointA = pointB = null;
  47614. }
  47615. }
  47616. if (!noPreventDefault) {
  47617. evt.preventDefault();
  47618. }
  47619. }
  47620. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47621. if (!noPreventDefault) {
  47622. evt.preventDefault();
  47623. }
  47624. // One button down
  47625. if (pointA && pointB === null && cacheSoloPointer) {
  47626. if (_this.panningSensibility !== 0 &&
  47627. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47628. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47629. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47630. }
  47631. else {
  47632. var offsetX = evt.clientX - cacheSoloPointer.x;
  47633. var offsetY = evt.clientY - cacheSoloPointer.y;
  47634. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47635. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47636. }
  47637. cacheSoloPointer.x = evt.clientX;
  47638. cacheSoloPointer.y = evt.clientY;
  47639. }
  47640. // Two buttons down: pinch/pan
  47641. else if (pointA && pointB) {
  47642. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47643. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47644. ed.x = evt.clientX;
  47645. ed.y = evt.clientY;
  47646. var direction = _this.pinchInwards ? 1 : -1;
  47647. var distX = pointA.x - pointB.x;
  47648. var distY = pointA.y - pointB.y;
  47649. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47650. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47651. if (previousPinchSquaredDistance === 0) {
  47652. initialDistance = pinchDistance;
  47653. previousPinchSquaredDistance = pinchSquaredDistance;
  47654. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47655. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47656. return;
  47657. }
  47658. if (_this.multiTouchPanAndZoom) {
  47659. if (_this.pinchDeltaPercentage) {
  47660. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47661. }
  47662. else {
  47663. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47664. (_this.pinchPrecision *
  47665. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47666. direction);
  47667. }
  47668. if (_this.panningSensibility !== 0) {
  47669. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47670. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47671. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47672. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47673. previousMultiTouchPanPosition.x = pointersCenterX;
  47674. previousMultiTouchPanPosition.y = pointersCenterY;
  47675. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47676. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47677. }
  47678. }
  47679. else {
  47680. twoFingerActivityCount++;
  47681. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47682. if (_this.pinchDeltaPercentage) {
  47683. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47684. }
  47685. else {
  47686. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47687. (_this.pinchPrecision *
  47688. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47689. direction);
  47690. }
  47691. previousMultiTouchPanPosition.isPaning = false;
  47692. previousMultiTouchPanPosition.isPinching = true;
  47693. }
  47694. else {
  47695. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47696. if (!previousMultiTouchPanPosition.isPaning) {
  47697. previousMultiTouchPanPosition.isPaning = true;
  47698. previousMultiTouchPanPosition.isPinching = false;
  47699. previousMultiTouchPanPosition.x = ed.x;
  47700. previousMultiTouchPanPosition.y = ed.y;
  47701. return;
  47702. }
  47703. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47704. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47705. }
  47706. }
  47707. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47708. previousMultiTouchPanPosition.x = ed.x;
  47709. previousMultiTouchPanPosition.y = ed.y;
  47710. }
  47711. }
  47712. previousPinchSquaredDistance = pinchSquaredDistance;
  47713. }
  47714. }
  47715. };
  47716. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47717. this._onContextMenu = function (evt) {
  47718. evt.preventDefault();
  47719. };
  47720. if (!this.camera._useCtrlForPanning) {
  47721. element.addEventListener("contextmenu", this._onContextMenu, false);
  47722. }
  47723. this._onLostFocus = function () {
  47724. //this._keys = [];
  47725. pointA = pointB = null;
  47726. previousPinchSquaredDistance = 0;
  47727. previousMultiTouchPanPosition.isPaning = false;
  47728. previousMultiTouchPanPosition.isPinching = false;
  47729. twoFingerActivityCount = 0;
  47730. cacheSoloPointer = null;
  47731. initialDistance = 0;
  47732. };
  47733. this._onMouseMove = function (evt) {
  47734. if (!engine.isPointerLock) {
  47735. return;
  47736. }
  47737. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47738. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47739. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47740. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47741. if (!noPreventDefault) {
  47742. evt.preventDefault();
  47743. }
  47744. };
  47745. this._onGestureStart = function (e) {
  47746. if (window.MSGesture === undefined) {
  47747. return;
  47748. }
  47749. if (!_this._MSGestureHandler) {
  47750. _this._MSGestureHandler = new MSGesture();
  47751. _this._MSGestureHandler.target = element;
  47752. }
  47753. _this._MSGestureHandler.addPointer(e.pointerId);
  47754. };
  47755. this._onGesture = function (e) {
  47756. _this.camera.radius *= e.scale;
  47757. if (e.preventDefault) {
  47758. if (!noPreventDefault) {
  47759. e.stopPropagation();
  47760. e.preventDefault();
  47761. }
  47762. }
  47763. };
  47764. element.addEventListener("mousemove", this._onMouseMove, false);
  47765. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47766. element.addEventListener("MSGestureChange", this._onGesture, false);
  47767. BABYLON.Tools.RegisterTopRootEvents([
  47768. { name: "blur", handler: this._onLostFocus }
  47769. ]);
  47770. };
  47771. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47772. if (this._onLostFocus) {
  47773. BABYLON.Tools.UnregisterTopRootEvents([
  47774. { name: "blur", handler: this._onLostFocus }
  47775. ]);
  47776. }
  47777. if (element && this._observer) {
  47778. this.camera.getScene().onPointerObservable.remove(this._observer);
  47779. this._observer = null;
  47780. if (this._onContextMenu) {
  47781. element.removeEventListener("contextmenu", this._onContextMenu);
  47782. }
  47783. if (this._onMouseMove) {
  47784. element.removeEventListener("mousemove", this._onMouseMove);
  47785. }
  47786. if (this._onGestureStart) {
  47787. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47788. }
  47789. if (this._onGesture) {
  47790. element.removeEventListener("MSGestureChange", this._onGesture);
  47791. }
  47792. this._isPanClick = false;
  47793. this.pinchInwards = true;
  47794. this._onMouseMove = null;
  47795. this._onGestureStart = null;
  47796. this._onGesture = null;
  47797. this._MSGestureHandler = null;
  47798. this._onLostFocus = null;
  47799. this._onContextMenu = null;
  47800. }
  47801. };
  47802. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47803. return "ArcRotateCameraPointersInput";
  47804. };
  47805. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47806. return "pointers";
  47807. };
  47808. __decorate([
  47809. BABYLON.serialize()
  47810. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47811. __decorate([
  47812. BABYLON.serialize()
  47813. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47814. __decorate([
  47815. BABYLON.serialize()
  47816. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47817. __decorate([
  47818. BABYLON.serialize()
  47819. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47820. __decorate([
  47821. BABYLON.serialize()
  47822. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47823. __decorate([
  47824. BABYLON.serialize()
  47825. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47826. __decorate([
  47827. BABYLON.serialize()
  47828. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47829. __decorate([
  47830. BABYLON.serialize()
  47831. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47832. return ArcRotateCameraPointersInput;
  47833. }());
  47834. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47835. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47836. })(BABYLON || (BABYLON = {}));
  47837. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47838. var BABYLON;
  47839. (function (BABYLON) {
  47840. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47841. __extends(ArcRotateCameraInputsManager, _super);
  47842. function ArcRotateCameraInputsManager(camera) {
  47843. return _super.call(this, camera) || this;
  47844. }
  47845. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47846. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47847. return this;
  47848. };
  47849. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47850. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47851. return this;
  47852. };
  47853. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47854. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47855. return this;
  47856. };
  47857. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47858. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47859. return this;
  47860. };
  47861. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47862. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47863. return this;
  47864. };
  47865. return ArcRotateCameraInputsManager;
  47866. }(BABYLON.CameraInputsManager));
  47867. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47868. })(BABYLON || (BABYLON = {}));
  47869. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47870. var BABYLON;
  47871. (function (BABYLON) {
  47872. var ArcRotateCamera = /** @class */ (function (_super) {
  47873. __extends(ArcRotateCamera, _super);
  47874. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47875. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47876. _this.inertialAlphaOffset = 0;
  47877. _this.inertialBetaOffset = 0;
  47878. _this.inertialRadiusOffset = 0;
  47879. _this.lowerAlphaLimit = null;
  47880. _this.upperAlphaLimit = null;
  47881. _this.lowerBetaLimit = 0.01;
  47882. _this.upperBetaLimit = Math.PI;
  47883. _this.lowerRadiusLimit = null;
  47884. _this.upperRadiusLimit = null;
  47885. _this.inertialPanningX = 0;
  47886. _this.inertialPanningY = 0;
  47887. _this.pinchToPanMaxDistance = 20;
  47888. _this.panningDistanceLimit = null;
  47889. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47890. _this.panningInertia = 0.9;
  47891. //-- end properties for backward compatibility for inputs
  47892. _this.zoomOnFactor = 1;
  47893. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47894. _this.allowUpsideDown = true;
  47895. _this._viewMatrix = new BABYLON.Matrix();
  47896. // Panning
  47897. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47898. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47899. _this.checkCollisions = false;
  47900. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47901. _this._previousPosition = BABYLON.Vector3.Zero();
  47902. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47903. _this._newPosition = BABYLON.Vector3.Zero();
  47904. _this._computationVector = BABYLON.Vector3.Zero();
  47905. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47906. if (collidedMesh === void 0) { collidedMesh = null; }
  47907. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47908. newPosition.multiplyInPlace(_this._collider._radius);
  47909. }
  47910. if (!collidedMesh) {
  47911. _this._previousPosition.copyFrom(_this.position);
  47912. }
  47913. else {
  47914. _this.setPosition(newPosition);
  47915. if (_this.onCollide) {
  47916. _this.onCollide(collidedMesh);
  47917. }
  47918. }
  47919. // Recompute because of constraints
  47920. var cosa = Math.cos(_this.alpha);
  47921. var sina = Math.sin(_this.alpha);
  47922. var cosb = Math.cos(_this.beta);
  47923. var sinb = Math.sin(_this.beta);
  47924. if (sinb === 0) {
  47925. sinb = 0.0001;
  47926. }
  47927. var target = _this._getTargetPosition();
  47928. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47929. target.addToRef(_this._computationVector, _this._newPosition);
  47930. _this.position.copyFrom(_this._newPosition);
  47931. var up = _this.upVector;
  47932. if (_this.allowUpsideDown && _this.beta < 0) {
  47933. up = up.clone();
  47934. up = up.negate();
  47935. }
  47936. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47937. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47938. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47939. _this._collisionTriggered = false;
  47940. };
  47941. _this._target = BABYLON.Vector3.Zero();
  47942. if (target) {
  47943. _this.setTarget(target);
  47944. }
  47945. _this.alpha = alpha;
  47946. _this.beta = beta;
  47947. _this.radius = radius;
  47948. _this.getViewMatrix();
  47949. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47950. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47951. return _this;
  47952. }
  47953. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47954. get: function () {
  47955. return this._target;
  47956. },
  47957. set: function (value) {
  47958. this.setTarget(value);
  47959. },
  47960. enumerable: true,
  47961. configurable: true
  47962. });
  47963. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47964. //-- begin properties for backward compatibility for inputs
  47965. get: function () {
  47966. var pointers = this.inputs.attached["pointers"];
  47967. if (pointers)
  47968. return pointers.angularSensibilityX;
  47969. return 0;
  47970. },
  47971. set: function (value) {
  47972. var pointers = this.inputs.attached["pointers"];
  47973. if (pointers) {
  47974. pointers.angularSensibilityX = value;
  47975. }
  47976. },
  47977. enumerable: true,
  47978. configurable: true
  47979. });
  47980. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47981. get: function () {
  47982. var pointers = this.inputs.attached["pointers"];
  47983. if (pointers)
  47984. return pointers.angularSensibilityY;
  47985. return 0;
  47986. },
  47987. set: function (value) {
  47988. var pointers = this.inputs.attached["pointers"];
  47989. if (pointers) {
  47990. pointers.angularSensibilityY = value;
  47991. }
  47992. },
  47993. enumerable: true,
  47994. configurable: true
  47995. });
  47996. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47997. get: function () {
  47998. var pointers = this.inputs.attached["pointers"];
  47999. if (pointers)
  48000. return pointers.pinchPrecision;
  48001. return 0;
  48002. },
  48003. set: function (value) {
  48004. var pointers = this.inputs.attached["pointers"];
  48005. if (pointers) {
  48006. pointers.pinchPrecision = value;
  48007. }
  48008. },
  48009. enumerable: true,
  48010. configurable: true
  48011. });
  48012. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48013. get: function () {
  48014. var pointers = this.inputs.attached["pointers"];
  48015. if (pointers)
  48016. return pointers.pinchDeltaPercentage;
  48017. return 0;
  48018. },
  48019. set: function (value) {
  48020. var pointers = this.inputs.attached["pointers"];
  48021. if (pointers) {
  48022. pointers.pinchDeltaPercentage = value;
  48023. }
  48024. },
  48025. enumerable: true,
  48026. configurable: true
  48027. });
  48028. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48029. get: function () {
  48030. var pointers = this.inputs.attached["pointers"];
  48031. if (pointers)
  48032. return pointers.panningSensibility;
  48033. return 0;
  48034. },
  48035. set: function (value) {
  48036. var pointers = this.inputs.attached["pointers"];
  48037. if (pointers) {
  48038. pointers.panningSensibility = value;
  48039. }
  48040. },
  48041. enumerable: true,
  48042. configurable: true
  48043. });
  48044. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48045. get: function () {
  48046. var keyboard = this.inputs.attached["keyboard"];
  48047. if (keyboard)
  48048. return keyboard.keysUp;
  48049. return [];
  48050. },
  48051. set: function (value) {
  48052. var keyboard = this.inputs.attached["keyboard"];
  48053. if (keyboard)
  48054. keyboard.keysUp = value;
  48055. },
  48056. enumerable: true,
  48057. configurable: true
  48058. });
  48059. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48060. get: function () {
  48061. var keyboard = this.inputs.attached["keyboard"];
  48062. if (keyboard)
  48063. return keyboard.keysDown;
  48064. return [];
  48065. },
  48066. set: function (value) {
  48067. var keyboard = this.inputs.attached["keyboard"];
  48068. if (keyboard)
  48069. keyboard.keysDown = value;
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48075. get: function () {
  48076. var keyboard = this.inputs.attached["keyboard"];
  48077. if (keyboard)
  48078. return keyboard.keysLeft;
  48079. return [];
  48080. },
  48081. set: function (value) {
  48082. var keyboard = this.inputs.attached["keyboard"];
  48083. if (keyboard)
  48084. keyboard.keysLeft = value;
  48085. },
  48086. enumerable: true,
  48087. configurable: true
  48088. });
  48089. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48090. get: function () {
  48091. var keyboard = this.inputs.attached["keyboard"];
  48092. if (keyboard)
  48093. return keyboard.keysRight;
  48094. return [];
  48095. },
  48096. set: function (value) {
  48097. var keyboard = this.inputs.attached["keyboard"];
  48098. if (keyboard)
  48099. keyboard.keysRight = value;
  48100. },
  48101. enumerable: true,
  48102. configurable: true
  48103. });
  48104. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48105. get: function () {
  48106. var mousewheel = this.inputs.attached["mousewheel"];
  48107. if (mousewheel)
  48108. return mousewheel.wheelPrecision;
  48109. return 0;
  48110. },
  48111. set: function (value) {
  48112. var mousewheel = this.inputs.attached["mousewheel"];
  48113. if (mousewheel)
  48114. mousewheel.wheelPrecision = value;
  48115. },
  48116. enumerable: true,
  48117. configurable: true
  48118. });
  48119. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48120. get: function () {
  48121. var mousewheel = this.inputs.attached["mousewheel"];
  48122. if (mousewheel)
  48123. return mousewheel.wheelDeltaPercentage;
  48124. return 0;
  48125. },
  48126. set: function (value) {
  48127. var mousewheel = this.inputs.attached["mousewheel"];
  48128. if (mousewheel)
  48129. mousewheel.wheelDeltaPercentage = value;
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48135. get: function () {
  48136. return this._bouncingBehavior;
  48137. },
  48138. enumerable: true,
  48139. configurable: true
  48140. });
  48141. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48142. get: function () {
  48143. return this._bouncingBehavior != null;
  48144. },
  48145. set: function (value) {
  48146. if (value === this.useBouncingBehavior) {
  48147. return;
  48148. }
  48149. if (value) {
  48150. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48151. this.addBehavior(this._bouncingBehavior);
  48152. }
  48153. else if (this._bouncingBehavior) {
  48154. this.removeBehavior(this._bouncingBehavior);
  48155. this._bouncingBehavior = null;
  48156. }
  48157. },
  48158. enumerable: true,
  48159. configurable: true
  48160. });
  48161. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48162. get: function () {
  48163. return this._framingBehavior;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48169. get: function () {
  48170. return this._framingBehavior != null;
  48171. },
  48172. set: function (value) {
  48173. if (value === this.useFramingBehavior) {
  48174. return;
  48175. }
  48176. if (value) {
  48177. this._framingBehavior = new BABYLON.FramingBehavior();
  48178. this.addBehavior(this._framingBehavior);
  48179. }
  48180. else if (this._framingBehavior) {
  48181. this.removeBehavior(this._framingBehavior);
  48182. this._framingBehavior = null;
  48183. }
  48184. },
  48185. enumerable: true,
  48186. configurable: true
  48187. });
  48188. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48189. get: function () {
  48190. return this._autoRotationBehavior;
  48191. },
  48192. enumerable: true,
  48193. configurable: true
  48194. });
  48195. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48196. get: function () {
  48197. return this._autoRotationBehavior != null;
  48198. },
  48199. set: function (value) {
  48200. if (value === this.useAutoRotationBehavior) {
  48201. return;
  48202. }
  48203. if (value) {
  48204. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48205. this.addBehavior(this._autoRotationBehavior);
  48206. }
  48207. else if (this._autoRotationBehavior) {
  48208. this.removeBehavior(this._autoRotationBehavior);
  48209. this._autoRotationBehavior = null;
  48210. }
  48211. },
  48212. enumerable: true,
  48213. configurable: true
  48214. });
  48215. // Cache
  48216. ArcRotateCamera.prototype._initCache = function () {
  48217. _super.prototype._initCache.call(this);
  48218. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48219. this._cache.alpha = undefined;
  48220. this._cache.beta = undefined;
  48221. this._cache.radius = undefined;
  48222. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48223. };
  48224. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48225. if (!ignoreParentClass) {
  48226. _super.prototype._updateCache.call(this);
  48227. }
  48228. this._cache._target.copyFrom(this._getTargetPosition());
  48229. this._cache.alpha = this.alpha;
  48230. this._cache.beta = this.beta;
  48231. this._cache.radius = this.radius;
  48232. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48233. };
  48234. ArcRotateCamera.prototype._getTargetPosition = function () {
  48235. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48236. var pos = this._targetHost.getAbsolutePosition();
  48237. if (this._targetBoundingCenter) {
  48238. pos.addToRef(this._targetBoundingCenter, this._target);
  48239. }
  48240. else {
  48241. this._target.copyFrom(pos);
  48242. }
  48243. }
  48244. var lockedTargetPosition = this._getLockedTargetPosition();
  48245. if (lockedTargetPosition) {
  48246. return lockedTargetPosition;
  48247. }
  48248. return this._target;
  48249. };
  48250. ArcRotateCamera.prototype.storeState = function () {
  48251. this._storedAlpha = this.alpha;
  48252. this._storedBeta = this.beta;
  48253. this._storedRadius = this.radius;
  48254. this._storedTarget = this._getTargetPosition().clone();
  48255. return _super.prototype.storeState.call(this);
  48256. };
  48257. /**
  48258. * Restored camera state. You must call storeState() first
  48259. */
  48260. ArcRotateCamera.prototype._restoreStateValues = function () {
  48261. if (!_super.prototype._restoreStateValues.call(this)) {
  48262. return false;
  48263. }
  48264. this.alpha = this._storedAlpha;
  48265. this.beta = this._storedBeta;
  48266. this.radius = this._storedRadius;
  48267. this.setTarget(this._storedTarget.clone());
  48268. this.inertialAlphaOffset = 0;
  48269. this.inertialBetaOffset = 0;
  48270. this.inertialRadiusOffset = 0;
  48271. this.inertialPanningX = 0;
  48272. this.inertialPanningY = 0;
  48273. return true;
  48274. };
  48275. // Synchronized
  48276. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48277. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48278. return false;
  48279. return this._cache._target.equals(this._getTargetPosition())
  48280. && this._cache.alpha === this.alpha
  48281. && this._cache.beta === this.beta
  48282. && this._cache.radius === this.radius
  48283. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48284. };
  48285. // Methods
  48286. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48287. var _this = this;
  48288. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48289. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48290. this._useCtrlForPanning = useCtrlForPanning;
  48291. this._panningMouseButton = panningMouseButton;
  48292. this.inputs.attachElement(element, noPreventDefault);
  48293. this._reset = function () {
  48294. _this.inertialAlphaOffset = 0;
  48295. _this.inertialBetaOffset = 0;
  48296. _this.inertialRadiusOffset = 0;
  48297. _this.inertialPanningX = 0;
  48298. _this.inertialPanningY = 0;
  48299. };
  48300. };
  48301. ArcRotateCamera.prototype.detachControl = function (element) {
  48302. this.inputs.detachElement(element);
  48303. if (this._reset) {
  48304. this._reset();
  48305. }
  48306. };
  48307. ArcRotateCamera.prototype._checkInputs = function () {
  48308. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48309. if (this._collisionTriggered) {
  48310. return;
  48311. }
  48312. this.inputs.checkInputs();
  48313. // Inertia
  48314. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48315. if (this.getScene().useRightHandedSystem) {
  48316. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48317. }
  48318. else {
  48319. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48320. }
  48321. this.beta += this.inertialBetaOffset;
  48322. this.radius -= this.inertialRadiusOffset;
  48323. this.inertialAlphaOffset *= this.inertia;
  48324. this.inertialBetaOffset *= this.inertia;
  48325. this.inertialRadiusOffset *= this.inertia;
  48326. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48327. this.inertialAlphaOffset = 0;
  48328. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48329. this.inertialBetaOffset = 0;
  48330. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48331. this.inertialRadiusOffset = 0;
  48332. }
  48333. // Panning inertia
  48334. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48335. if (!this._localDirection) {
  48336. this._localDirection = BABYLON.Vector3.Zero();
  48337. this._transformedDirection = BABYLON.Vector3.Zero();
  48338. }
  48339. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48340. this._localDirection.multiplyInPlace(this.panningAxis);
  48341. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48342. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48343. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48344. if (!this.panningAxis.y) {
  48345. this._transformedDirection.y = 0;
  48346. }
  48347. if (!this._targetHost) {
  48348. if (this.panningDistanceLimit) {
  48349. this._transformedDirection.addInPlace(this._target);
  48350. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48351. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48352. this._target.copyFrom(this._transformedDirection);
  48353. }
  48354. }
  48355. else {
  48356. this._target.addInPlace(this._transformedDirection);
  48357. }
  48358. }
  48359. this.inertialPanningX *= this.panningInertia;
  48360. this.inertialPanningY *= this.panningInertia;
  48361. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48362. this.inertialPanningX = 0;
  48363. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48364. this.inertialPanningY = 0;
  48365. }
  48366. // Limits
  48367. this._checkLimits();
  48368. _super.prototype._checkInputs.call(this);
  48369. };
  48370. ArcRotateCamera.prototype._checkLimits = function () {
  48371. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48372. if (this.allowUpsideDown && this.beta > Math.PI) {
  48373. this.beta = this.beta - (2 * Math.PI);
  48374. }
  48375. }
  48376. else {
  48377. if (this.beta < this.lowerBetaLimit) {
  48378. this.beta = this.lowerBetaLimit;
  48379. }
  48380. }
  48381. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48382. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48383. this.beta = this.beta + (2 * Math.PI);
  48384. }
  48385. }
  48386. else {
  48387. if (this.beta > this.upperBetaLimit) {
  48388. this.beta = this.upperBetaLimit;
  48389. }
  48390. }
  48391. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48392. this.alpha = this.lowerAlphaLimit;
  48393. }
  48394. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48395. this.alpha = this.upperAlphaLimit;
  48396. }
  48397. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48398. this.radius = this.lowerRadiusLimit;
  48399. }
  48400. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48401. this.radius = this.upperRadiusLimit;
  48402. }
  48403. };
  48404. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48405. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48406. this.radius = this._computationVector.length();
  48407. if (this.radius === 0) {
  48408. this.radius = 0.0001; // Just to avoid division by zero
  48409. }
  48410. // Alpha
  48411. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48412. if (this._computationVector.z < 0) {
  48413. this.alpha = 2 * Math.PI - this.alpha;
  48414. }
  48415. // Beta
  48416. this.beta = Math.acos(this._computationVector.y / this.radius);
  48417. this._checkLimits();
  48418. };
  48419. ArcRotateCamera.prototype.setPosition = function (position) {
  48420. if (this.position.equals(position)) {
  48421. return;
  48422. }
  48423. this.position.copyFrom(position);
  48424. this.rebuildAnglesAndRadius();
  48425. };
  48426. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48427. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48428. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48429. if (target.getBoundingInfo) {
  48430. if (toBoundingCenter) {
  48431. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48432. }
  48433. else {
  48434. this._targetBoundingCenter = null;
  48435. }
  48436. this._targetHost = target;
  48437. this._target = this._getTargetPosition();
  48438. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48439. }
  48440. else {
  48441. var newTarget = target;
  48442. var currentTarget = this._getTargetPosition();
  48443. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48444. return;
  48445. }
  48446. this._targetHost = null;
  48447. this._target = newTarget;
  48448. this._targetBoundingCenter = null;
  48449. this.onMeshTargetChangedObservable.notifyObservers(null);
  48450. }
  48451. this.rebuildAnglesAndRadius();
  48452. };
  48453. ArcRotateCamera.prototype._getViewMatrix = function () {
  48454. // Compute
  48455. var cosa = Math.cos(this.alpha);
  48456. var sina = Math.sin(this.alpha);
  48457. var cosb = Math.cos(this.beta);
  48458. var sinb = Math.sin(this.beta);
  48459. if (sinb === 0) {
  48460. sinb = 0.0001;
  48461. }
  48462. var target = this._getTargetPosition();
  48463. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48464. target.addToRef(this._computationVector, this._newPosition);
  48465. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48466. if (!this._collider) {
  48467. this._collider = new BABYLON.Collider();
  48468. }
  48469. this._collider._radius = this.collisionRadius;
  48470. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48471. this._collisionTriggered = true;
  48472. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48473. }
  48474. else {
  48475. this.position.copyFrom(this._newPosition);
  48476. var up = this.upVector;
  48477. if (this.allowUpsideDown && sinb < 0) {
  48478. up = up.clone();
  48479. up = up.negate();
  48480. }
  48481. if (this.getScene().useRightHandedSystem) {
  48482. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48483. }
  48484. else {
  48485. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48486. }
  48487. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48488. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48489. }
  48490. this._currentTarget = target;
  48491. return this._viewMatrix;
  48492. };
  48493. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48494. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48495. meshes = meshes || this.getScene().meshes;
  48496. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48497. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48498. this.radius = distance * this.zoomOnFactor;
  48499. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48500. };
  48501. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48502. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48503. var meshesOrMinMaxVector;
  48504. var distance;
  48505. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48506. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48507. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48508. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48509. }
  48510. else { //minMaxVector and distance
  48511. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48512. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48513. distance = minMaxVectorAndDistance.distance;
  48514. }
  48515. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48516. if (!doNotUpdateMaxZ) {
  48517. this.maxZ = distance * 2;
  48518. }
  48519. };
  48520. /**
  48521. * @override
  48522. * Override Camera.createRigCamera
  48523. */
  48524. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48525. var alphaShift = 0;
  48526. switch (this.cameraRigMode) {
  48527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48530. case BABYLON.Camera.RIG_MODE_VR:
  48531. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48532. break;
  48533. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48534. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48535. break;
  48536. }
  48537. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48538. rigCam._cameraRigParams = {};
  48539. return rigCam;
  48540. };
  48541. /**
  48542. * @override
  48543. * Override Camera._updateRigCameras
  48544. */
  48545. ArcRotateCamera.prototype._updateRigCameras = function () {
  48546. var camLeft = this._rigCameras[0];
  48547. var camRight = this._rigCameras[1];
  48548. camLeft.beta = camRight.beta = this.beta;
  48549. camLeft.radius = camRight.radius = this.radius;
  48550. switch (this.cameraRigMode) {
  48551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48554. case BABYLON.Camera.RIG_MODE_VR:
  48555. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48556. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48557. break;
  48558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48559. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48560. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48561. break;
  48562. }
  48563. _super.prototype._updateRigCameras.call(this);
  48564. };
  48565. ArcRotateCamera.prototype.dispose = function () {
  48566. this.inputs.clear();
  48567. _super.prototype.dispose.call(this);
  48568. };
  48569. ArcRotateCamera.prototype.getClassName = function () {
  48570. return "ArcRotateCamera";
  48571. };
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], ArcRotateCamera.prototype, "alpha", void 0);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], ArcRotateCamera.prototype, "beta", void 0);
  48578. __decorate([
  48579. BABYLON.serialize()
  48580. ], ArcRotateCamera.prototype, "radius", void 0);
  48581. __decorate([
  48582. BABYLON.serializeAsVector3("target")
  48583. ], ArcRotateCamera.prototype, "_target", void 0);
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48587. __decorate([
  48588. BABYLON.serialize()
  48589. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48590. __decorate([
  48591. BABYLON.serialize()
  48592. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48593. __decorate([
  48594. BABYLON.serialize()
  48595. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48608. __decorate([
  48609. BABYLON.serialize()
  48610. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48611. __decorate([
  48612. BABYLON.serialize()
  48613. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48614. __decorate([
  48615. BABYLON.serialize()
  48616. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48617. __decorate([
  48618. BABYLON.serialize()
  48619. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48620. __decorate([
  48621. BABYLON.serialize()
  48622. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48623. __decorate([
  48624. BABYLON.serializeAsVector3()
  48625. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48626. __decorate([
  48627. BABYLON.serialize()
  48628. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48629. __decorate([
  48630. BABYLON.serialize()
  48631. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48632. __decorate([
  48633. BABYLON.serialize()
  48634. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48635. return ArcRotateCamera;
  48636. }(BABYLON.TargetCamera));
  48637. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48638. })(BABYLON || (BABYLON = {}));
  48639. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48640. var BABYLON;
  48641. (function (BABYLON) {
  48642. /**
  48643. * The HemisphericLight simulates the ambient environment light,
  48644. * so the passed direction is the light reflection direction, not the incoming direction.
  48645. */
  48646. var HemisphericLight = /** @class */ (function (_super) {
  48647. __extends(HemisphericLight, _super);
  48648. /**
  48649. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48650. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48651. * The HemisphericLight can't cast shadows.
  48652. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48653. * @param name The friendly name of the light
  48654. * @param direction The direction of the light reflection
  48655. * @param scene The scene the light belongs to
  48656. */
  48657. function HemisphericLight(name, direction, scene) {
  48658. var _this = _super.call(this, name, scene) || this;
  48659. /**
  48660. * The groundColor is the light in the opposite direction to the one specified during creation.
  48661. * 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.
  48662. */
  48663. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48664. _this.direction = direction || BABYLON.Vector3.Up();
  48665. return _this;
  48666. }
  48667. HemisphericLight.prototype._buildUniformLayout = function () {
  48668. this._uniformBuffer.addUniform("vLightData", 4);
  48669. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48670. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48671. this._uniformBuffer.addUniform("vLightGround", 3);
  48672. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48673. this._uniformBuffer.addUniform("depthValues", 2);
  48674. this._uniformBuffer.create();
  48675. };
  48676. /**
  48677. * Returns the string "HemisphericLight".
  48678. * @return The class name
  48679. */
  48680. HemisphericLight.prototype.getClassName = function () {
  48681. return "HemisphericLight";
  48682. };
  48683. /**
  48684. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48685. * Returns the updated direction.
  48686. * @param target The target the direction should point to
  48687. * @return The computed direction
  48688. */
  48689. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48690. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48691. return this.direction;
  48692. };
  48693. /**
  48694. * Returns the shadow generator associated to the light.
  48695. * @returns Always null for hemispheric lights because it does not support shadows.
  48696. */
  48697. HemisphericLight.prototype.getShadowGenerator = function () {
  48698. return null;
  48699. };
  48700. /**
  48701. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48702. * @param effect The effect to update
  48703. * @param lightIndex The index of the light in the effect to update
  48704. * @returns The hemispheric light
  48705. */
  48706. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48707. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48708. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48709. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48710. return this;
  48711. };
  48712. /**
  48713. * @ignore internal use only.
  48714. */
  48715. HemisphericLight.prototype._getWorldMatrix = function () {
  48716. if (!this._worldMatrix) {
  48717. this._worldMatrix = BABYLON.Matrix.Identity();
  48718. }
  48719. return this._worldMatrix;
  48720. };
  48721. /**
  48722. * Returns the integer 3.
  48723. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48724. */
  48725. HemisphericLight.prototype.getTypeID = function () {
  48726. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48727. };
  48728. __decorate([
  48729. BABYLON.serializeAsColor3()
  48730. ], HemisphericLight.prototype, "groundColor", void 0);
  48731. __decorate([
  48732. BABYLON.serializeAsVector3()
  48733. ], HemisphericLight.prototype, "direction", void 0);
  48734. return HemisphericLight;
  48735. }(BABYLON.Light));
  48736. BABYLON.HemisphericLight = HemisphericLight;
  48737. })(BABYLON || (BABYLON = {}));
  48738. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48739. var BABYLON;
  48740. (function (BABYLON) {
  48741. /**
  48742. * Base implementation IShadowLight
  48743. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48744. */
  48745. var ShadowLight = /** @class */ (function (_super) {
  48746. __extends(ShadowLight, _super);
  48747. function ShadowLight() {
  48748. var _this = _super !== null && _super.apply(this, arguments) || this;
  48749. _this._needProjectionMatrixCompute = true;
  48750. return _this;
  48751. }
  48752. ShadowLight.prototype._setPosition = function (value) {
  48753. this._position = value;
  48754. };
  48755. Object.defineProperty(ShadowLight.prototype, "position", {
  48756. /**
  48757. * Sets the position the shadow will be casted from. Also use as the light position for both
  48758. * point and spot lights.
  48759. */
  48760. get: function () {
  48761. return this._position;
  48762. },
  48763. /**
  48764. * Sets the position the shadow will be casted from. Also use as the light position for both
  48765. * point and spot lights.
  48766. */
  48767. set: function (value) {
  48768. this._setPosition(value);
  48769. },
  48770. enumerable: true,
  48771. configurable: true
  48772. });
  48773. ShadowLight.prototype._setDirection = function (value) {
  48774. this._direction = value;
  48775. };
  48776. Object.defineProperty(ShadowLight.prototype, "direction", {
  48777. /**
  48778. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48779. * Also use as the light direction on spot and directional lights.
  48780. */
  48781. get: function () {
  48782. return this._direction;
  48783. },
  48784. /**
  48785. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48786. * Also use as the light direction on spot and directional lights.
  48787. */
  48788. set: function (value) {
  48789. this._setDirection(value);
  48790. },
  48791. enumerable: true,
  48792. configurable: true
  48793. });
  48794. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48795. /**
  48796. * Gets the shadow projection clipping minimum z value.
  48797. */
  48798. get: function () {
  48799. return this._shadowMinZ;
  48800. },
  48801. /**
  48802. * Sets the shadow projection clipping minimum z value.
  48803. */
  48804. set: function (value) {
  48805. this._shadowMinZ = value;
  48806. this.forceProjectionMatrixCompute();
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48812. /**
  48813. * Sets the shadow projection clipping maximum z value.
  48814. */
  48815. get: function () {
  48816. return this._shadowMaxZ;
  48817. },
  48818. /**
  48819. * Gets the shadow projection clipping maximum z value.
  48820. */
  48821. set: function (value) {
  48822. this._shadowMaxZ = value;
  48823. this.forceProjectionMatrixCompute();
  48824. },
  48825. enumerable: true,
  48826. configurable: true
  48827. });
  48828. /**
  48829. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48830. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48831. */
  48832. ShadowLight.prototype.computeTransformedInformation = function () {
  48833. if (this.parent && this.parent.getWorldMatrix) {
  48834. if (!this.transformedPosition) {
  48835. this.transformedPosition = BABYLON.Vector3.Zero();
  48836. }
  48837. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48838. // In case the direction is present.
  48839. if (this.direction) {
  48840. if (!this.transformedDirection) {
  48841. this.transformedDirection = BABYLON.Vector3.Zero();
  48842. }
  48843. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48844. }
  48845. return true;
  48846. }
  48847. return false;
  48848. };
  48849. /**
  48850. * Return the depth scale used for the shadow map.
  48851. * @returns the depth scale.
  48852. */
  48853. ShadowLight.prototype.getDepthScale = function () {
  48854. return 50.0;
  48855. };
  48856. /**
  48857. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48858. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48859. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48860. */
  48861. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48862. return this.transformedDirection ? this.transformedDirection : this.direction;
  48863. };
  48864. /**
  48865. * Returns the ShadowLight absolute position in the World.
  48866. * @returns the position vector in world space
  48867. */
  48868. ShadowLight.prototype.getAbsolutePosition = function () {
  48869. return this.transformedPosition ? this.transformedPosition : this.position;
  48870. };
  48871. /**
  48872. * Sets the ShadowLight direction toward the passed target.
  48873. * @param target The point tot target in local space
  48874. * @returns the updated ShadowLight direction
  48875. */
  48876. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48877. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48878. return this.direction;
  48879. };
  48880. /**
  48881. * Returns the light rotation in euler definition.
  48882. * @returns the x y z rotation in local space.
  48883. */
  48884. ShadowLight.prototype.getRotation = function () {
  48885. this.direction.normalize();
  48886. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48887. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48888. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48889. };
  48890. /**
  48891. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48892. * @returns true if a cube texture needs to be use
  48893. */
  48894. ShadowLight.prototype.needCube = function () {
  48895. return false;
  48896. };
  48897. /**
  48898. * Detects if the projection matrix requires to be recomputed this frame.
  48899. * @returns true if it requires to be recomputed otherwise, false.
  48900. */
  48901. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48902. return this._needProjectionMatrixCompute;
  48903. };
  48904. /**
  48905. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48906. */
  48907. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48908. this._needProjectionMatrixCompute = true;
  48909. };
  48910. /**
  48911. * Get the world matrix of the sahdow lights.
  48912. * @ignore Internal Use Only
  48913. */
  48914. ShadowLight.prototype._getWorldMatrix = function () {
  48915. if (!this._worldMatrix) {
  48916. this._worldMatrix = BABYLON.Matrix.Identity();
  48917. }
  48918. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48919. return this._worldMatrix;
  48920. };
  48921. /**
  48922. * Gets the minZ used for shadow according to both the scene and the light.
  48923. * @param activeCamera The camera we are returning the min for
  48924. * @returns the depth min z
  48925. */
  48926. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48927. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48928. };
  48929. /**
  48930. * Gets the maxZ used for shadow according to both the scene and the light.
  48931. * @param activeCamera The camera we are returning the max for
  48932. * @returns the depth max z
  48933. */
  48934. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48935. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48936. };
  48937. /**
  48938. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48939. * @param matrix The materix to updated with the projection information
  48940. * @param viewMatrix The transform matrix of the light
  48941. * @param renderList The list of mesh to render in the map
  48942. * @returns The current light
  48943. */
  48944. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48945. if (this.customProjectionMatrixBuilder) {
  48946. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48947. }
  48948. else {
  48949. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48950. }
  48951. return this;
  48952. };
  48953. __decorate([
  48954. BABYLON.serializeAsVector3()
  48955. ], ShadowLight.prototype, "position", null);
  48956. __decorate([
  48957. BABYLON.serializeAsVector3()
  48958. ], ShadowLight.prototype, "direction", null);
  48959. __decorate([
  48960. BABYLON.serialize()
  48961. ], ShadowLight.prototype, "shadowMinZ", null);
  48962. __decorate([
  48963. BABYLON.serialize()
  48964. ], ShadowLight.prototype, "shadowMaxZ", null);
  48965. return ShadowLight;
  48966. }(BABYLON.Light));
  48967. BABYLON.ShadowLight = ShadowLight;
  48968. })(BABYLON || (BABYLON = {}));
  48969. //# sourceMappingURL=babylon.shadowLight.js.map
  48970. var BABYLON;
  48971. (function (BABYLON) {
  48972. /**
  48973. * A point light is a light defined by an unique point in world space.
  48974. * The light is emitted in every direction from this point.
  48975. * A good example of a point light is a standard light bulb.
  48976. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48977. */
  48978. var PointLight = /** @class */ (function (_super) {
  48979. __extends(PointLight, _super);
  48980. /**
  48981. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48982. * A PointLight emits the light in every direction.
  48983. * It can cast shadows.
  48984. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48985. * ```javascript
  48986. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48987. * ```
  48988. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48989. * @param name The light friendly name
  48990. * @param position The position of the point light in the scene
  48991. * @param scene The scene the lights belongs to
  48992. */
  48993. function PointLight(name, position, scene) {
  48994. var _this = _super.call(this, name, scene) || this;
  48995. _this._shadowAngle = Math.PI / 2;
  48996. _this.position = position;
  48997. return _this;
  48998. }
  48999. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49000. /**
  49001. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49002. * This specifies what angle the shadow will use to be created.
  49003. *
  49004. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49005. */
  49006. get: function () {
  49007. return this._shadowAngle;
  49008. },
  49009. /**
  49010. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49011. * This specifies what angle the shadow will use to be created.
  49012. *
  49013. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49014. */
  49015. set: function (value) {
  49016. this._shadowAngle = value;
  49017. this.forceProjectionMatrixCompute();
  49018. },
  49019. enumerable: true,
  49020. configurable: true
  49021. });
  49022. Object.defineProperty(PointLight.prototype, "direction", {
  49023. /**
  49024. * Gets the direction if it has been set.
  49025. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49026. */
  49027. get: function () {
  49028. return this._direction;
  49029. },
  49030. /**
  49031. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49032. */
  49033. set: function (value) {
  49034. var previousNeedCube = this.needCube();
  49035. this._direction = value;
  49036. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49037. this._shadowGenerator.recreateShadowMap();
  49038. }
  49039. },
  49040. enumerable: true,
  49041. configurable: true
  49042. });
  49043. /**
  49044. * Returns the string "PointLight"
  49045. * @returns the class name
  49046. */
  49047. PointLight.prototype.getClassName = function () {
  49048. return "PointLight";
  49049. };
  49050. /**
  49051. * Returns the integer 0.
  49052. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49053. */
  49054. PointLight.prototype.getTypeID = function () {
  49055. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49056. };
  49057. /**
  49058. * Specifies wether or not the shadowmap should be a cube texture.
  49059. * @returns true if the shadowmap needs to be a cube texture.
  49060. */
  49061. PointLight.prototype.needCube = function () {
  49062. return !this.direction;
  49063. };
  49064. /**
  49065. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49066. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49067. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49068. */
  49069. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49070. if (this.direction) {
  49071. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49072. }
  49073. else {
  49074. switch (faceIndex) {
  49075. case 0:
  49076. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49077. case 1:
  49078. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49079. case 2:
  49080. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49081. case 3:
  49082. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49083. case 4:
  49084. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49085. case 5:
  49086. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49087. }
  49088. }
  49089. return BABYLON.Vector3.Zero();
  49090. };
  49091. /**
  49092. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49093. * - fov = PI / 2
  49094. * - aspect ratio : 1.0
  49095. * - z-near and far equal to the active camera minZ and maxZ.
  49096. * Returns the PointLight.
  49097. */
  49098. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49099. var activeCamera = this.getScene().activeCamera;
  49100. if (!activeCamera) {
  49101. return;
  49102. }
  49103. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49104. };
  49105. PointLight.prototype._buildUniformLayout = function () {
  49106. this._uniformBuffer.addUniform("vLightData", 4);
  49107. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49108. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49109. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49110. this._uniformBuffer.addUniform("depthValues", 2);
  49111. this._uniformBuffer.create();
  49112. };
  49113. /**
  49114. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49115. * @param effect The effect to update
  49116. * @param lightIndex The index of the light in the effect to update
  49117. * @returns The point light
  49118. */
  49119. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49120. if (this.computeTransformedInformation()) {
  49121. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49122. return this;
  49123. }
  49124. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49125. return this;
  49126. };
  49127. __decorate([
  49128. BABYLON.serialize()
  49129. ], PointLight.prototype, "shadowAngle", null);
  49130. return PointLight;
  49131. }(BABYLON.ShadowLight));
  49132. BABYLON.PointLight = PointLight;
  49133. })(BABYLON || (BABYLON = {}));
  49134. //# sourceMappingURL=babylon.pointLight.js.map
  49135. var BABYLON;
  49136. (function (BABYLON) {
  49137. /**
  49138. * A directional light is defined by a direction (what a surprise!).
  49139. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49140. * 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.
  49141. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49142. */
  49143. var DirectionalLight = /** @class */ (function (_super) {
  49144. __extends(DirectionalLight, _super);
  49145. /**
  49146. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49147. * The directional light is emitted from everywhere in the given direction.
  49148. * It can cast shawdows.
  49149. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49150. * @param name The friendly name of the light
  49151. * @param direction The direction of the light
  49152. * @param scene The scene the light belongs to
  49153. */
  49154. function DirectionalLight(name, direction, scene) {
  49155. var _this = _super.call(this, name, scene) || this;
  49156. _this._shadowFrustumSize = 0;
  49157. _this._shadowOrthoScale = 0.1;
  49158. /**
  49159. * Automatically compute the projection matrix to best fit (including all the casters)
  49160. * on each frame.
  49161. */
  49162. _this.autoUpdateExtends = true;
  49163. // Cache
  49164. _this._orthoLeft = Number.MAX_VALUE;
  49165. _this._orthoRight = Number.MIN_VALUE;
  49166. _this._orthoTop = Number.MIN_VALUE;
  49167. _this._orthoBottom = Number.MAX_VALUE;
  49168. _this.position = direction.scale(-1.0);
  49169. _this.direction = direction;
  49170. return _this;
  49171. }
  49172. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49173. /**
  49174. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49175. */
  49176. get: function () {
  49177. return this._shadowFrustumSize;
  49178. },
  49179. /**
  49180. * Specifies a fix frustum size for the shadow generation.
  49181. */
  49182. set: function (value) {
  49183. this._shadowFrustumSize = value;
  49184. this.forceProjectionMatrixCompute();
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49190. /**
  49191. * Gets the shadow projection scale against the optimal computed one.
  49192. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49193. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49194. */
  49195. get: function () {
  49196. return this._shadowOrthoScale;
  49197. },
  49198. /**
  49199. * Sets the shadow projection scale against the optimal computed one.
  49200. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49201. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49202. */
  49203. set: function (value) {
  49204. this._shadowOrthoScale = value;
  49205. this.forceProjectionMatrixCompute();
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. /**
  49211. * Returns the string "DirectionalLight".
  49212. * @return The class name
  49213. */
  49214. DirectionalLight.prototype.getClassName = function () {
  49215. return "DirectionalLight";
  49216. };
  49217. /**
  49218. * Returns the integer 1.
  49219. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49220. */
  49221. DirectionalLight.prototype.getTypeID = function () {
  49222. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49223. };
  49224. /**
  49225. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49226. * Returns the DirectionalLight Shadow projection matrix.
  49227. */
  49228. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49229. if (this.shadowFrustumSize > 0) {
  49230. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49231. }
  49232. else {
  49233. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49234. }
  49235. };
  49236. /**
  49237. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49238. * Returns the DirectionalLight Shadow projection matrix.
  49239. */
  49240. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49241. var activeCamera = this.getScene().activeCamera;
  49242. if (!activeCamera) {
  49243. return;
  49244. }
  49245. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49246. };
  49247. /**
  49248. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49249. * Returns the DirectionalLight Shadow projection matrix.
  49250. */
  49251. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49252. var activeCamera = this.getScene().activeCamera;
  49253. if (!activeCamera) {
  49254. return;
  49255. }
  49256. // Check extends
  49257. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49258. var tempVector3 = BABYLON.Vector3.Zero();
  49259. this._orthoLeft = Number.MAX_VALUE;
  49260. this._orthoRight = Number.MIN_VALUE;
  49261. this._orthoTop = Number.MIN_VALUE;
  49262. this._orthoBottom = Number.MAX_VALUE;
  49263. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49264. var mesh = renderList[meshIndex];
  49265. if (!mesh) {
  49266. continue;
  49267. }
  49268. var boundingInfo = mesh.getBoundingInfo();
  49269. var boundingBox = boundingInfo.boundingBox;
  49270. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49271. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49272. if (tempVector3.x < this._orthoLeft)
  49273. this._orthoLeft = tempVector3.x;
  49274. if (tempVector3.y < this._orthoBottom)
  49275. this._orthoBottom = tempVector3.y;
  49276. if (tempVector3.x > this._orthoRight)
  49277. this._orthoRight = tempVector3.x;
  49278. if (tempVector3.y > this._orthoTop)
  49279. this._orthoTop = tempVector3.y;
  49280. }
  49281. }
  49282. }
  49283. var xOffset = this._orthoRight - this._orthoLeft;
  49284. var yOffset = this._orthoTop - this._orthoBottom;
  49285. 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);
  49286. };
  49287. DirectionalLight.prototype._buildUniformLayout = function () {
  49288. this._uniformBuffer.addUniform("vLightData", 4);
  49289. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49290. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49291. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49292. this._uniformBuffer.addUniform("depthValues", 2);
  49293. this._uniformBuffer.create();
  49294. };
  49295. /**
  49296. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49297. * @param effect The effect to update
  49298. * @param lightIndex The index of the light in the effect to update
  49299. * @returns The directional light
  49300. */
  49301. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49302. if (this.computeTransformedInformation()) {
  49303. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49304. return this;
  49305. }
  49306. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49307. return this;
  49308. };
  49309. /**
  49310. * Gets the minZ used for shadow according to both the scene and the light.
  49311. *
  49312. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49313. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49314. * @param activeCamera The camera we are returning the min for
  49315. * @returns the depth min z
  49316. */
  49317. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49318. return 1;
  49319. };
  49320. /**
  49321. * Gets the maxZ used for shadow according to both the scene and the light.
  49322. *
  49323. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49324. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49325. * @param activeCamera The camera we are returning the max for
  49326. * @returns the depth max z
  49327. */
  49328. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49329. return 1;
  49330. };
  49331. __decorate([
  49332. BABYLON.serialize()
  49333. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49334. __decorate([
  49335. BABYLON.serialize()
  49336. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49340. return DirectionalLight;
  49341. }(BABYLON.ShadowLight));
  49342. BABYLON.DirectionalLight = DirectionalLight;
  49343. })(BABYLON || (BABYLON = {}));
  49344. //# sourceMappingURL=babylon.directionalLight.js.map
  49345. var BABYLON;
  49346. (function (BABYLON) {
  49347. /**
  49348. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49349. * These values define a cone of light starting from the position, emitting toward the direction.
  49350. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49351. * and the exponent defines the speed of the decay of the light with distance (reach).
  49352. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49353. */
  49354. var SpotLight = /** @class */ (function (_super) {
  49355. __extends(SpotLight, _super);
  49356. /**
  49357. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49358. * It can cast shadows.
  49359. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49360. * @param name The light friendly name
  49361. * @param position The position of the spot light in the scene
  49362. * @param direction The direction of the light in the scene
  49363. * @param angle The cone angle of the light in Radians
  49364. * @param exponent The light decay speed with the distance from the emission spot
  49365. * @param scene The scene the lights belongs to
  49366. */
  49367. function SpotLight(name, position, direction, angle, exponent, scene) {
  49368. var _this = _super.call(this, name, scene) || this;
  49369. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49370. _this._projectionTextureLightNear = 1e-6;
  49371. _this._projectionTextureLightFar = 1000.0;
  49372. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49373. _this._projectionTextureViewLightDirty = true;
  49374. _this._projectionTextureProjectionLightDirty = true;
  49375. _this._projectionTextureDirty = true;
  49376. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49377. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49378. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49379. _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);
  49380. _this.position = position;
  49381. _this.direction = direction;
  49382. _this.angle = angle;
  49383. _this.exponent = exponent;
  49384. return _this;
  49385. }
  49386. Object.defineProperty(SpotLight.prototype, "angle", {
  49387. /**
  49388. * Gets the cone angle of the spot light in Radians.
  49389. */
  49390. get: function () {
  49391. return this._angle;
  49392. },
  49393. /**
  49394. * Sets the cone angle of the spot light in Radians.
  49395. */
  49396. set: function (value) {
  49397. this._angle = value;
  49398. this._projectionTextureProjectionLightDirty = true;
  49399. this.forceProjectionMatrixCompute();
  49400. },
  49401. enumerable: true,
  49402. configurable: true
  49403. });
  49404. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49405. /**
  49406. * Allows scaling the angle of the light for shadow generation only.
  49407. */
  49408. get: function () {
  49409. return this._shadowAngleScale;
  49410. },
  49411. /**
  49412. * Allows scaling the angle of the light for shadow generation only.
  49413. */
  49414. set: function (value) {
  49415. this._shadowAngleScale = value;
  49416. this.forceProjectionMatrixCompute();
  49417. },
  49418. enumerable: true,
  49419. configurable: true
  49420. });
  49421. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49422. /**
  49423. * Allows reading the projecton texture
  49424. */
  49425. get: function () {
  49426. return this._projectionTextureMatrix;
  49427. },
  49428. enumerable: true,
  49429. configurable: true
  49430. });
  49431. ;
  49432. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49433. /**
  49434. * Gets the near clip of the Spotlight for texture projection.
  49435. */
  49436. get: function () {
  49437. return this._projectionTextureLightNear;
  49438. },
  49439. /**
  49440. * Sets the near clip of the Spotlight for texture projection.
  49441. */
  49442. set: function (value) {
  49443. this._projectionTextureLightNear = value;
  49444. this._projectionTextureProjectionLightDirty = true;
  49445. },
  49446. enumerable: true,
  49447. configurable: true
  49448. });
  49449. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49450. /**
  49451. * Gets the far clip of the Spotlight for texture projection.
  49452. */
  49453. get: function () {
  49454. return this._projectionTextureLightFar;
  49455. },
  49456. /**
  49457. * Sets the far clip of the Spotlight for texture projection.
  49458. */
  49459. set: function (value) {
  49460. this._projectionTextureLightFar = value;
  49461. this._projectionTextureProjectionLightDirty = true;
  49462. },
  49463. enumerable: true,
  49464. configurable: true
  49465. });
  49466. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49467. /**
  49468. * Gets the Up vector of the Spotlight for texture projection.
  49469. */
  49470. get: function () {
  49471. return this._projectionTextureUpDirection;
  49472. },
  49473. /**
  49474. * Sets the Up vector of the Spotlight for texture projection.
  49475. */
  49476. set: function (value) {
  49477. this._projectionTextureUpDirection = value;
  49478. this._projectionTextureProjectionLightDirty = true;
  49479. },
  49480. enumerable: true,
  49481. configurable: true
  49482. });
  49483. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49484. /**
  49485. * Gets the projection texture of the light.
  49486. */
  49487. get: function () {
  49488. return this._projectionTexture;
  49489. },
  49490. /**
  49491. * Sets the projection texture of the light.
  49492. */
  49493. set: function (value) {
  49494. this._projectionTexture = value;
  49495. this._projectionTextureDirty = true;
  49496. },
  49497. enumerable: true,
  49498. configurable: true
  49499. });
  49500. /**
  49501. * Returns the string "SpotLight".
  49502. * @returns the class name
  49503. */
  49504. SpotLight.prototype.getClassName = function () {
  49505. return "SpotLight";
  49506. };
  49507. /**
  49508. * Returns the integer 2.
  49509. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49510. */
  49511. SpotLight.prototype.getTypeID = function () {
  49512. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49513. };
  49514. /**
  49515. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49516. */
  49517. SpotLight.prototype._setDirection = function (value) {
  49518. _super.prototype._setDirection.call(this, value);
  49519. this._projectionTextureViewLightDirty = true;
  49520. };
  49521. /**
  49522. * Overrides the position setter to recompute the projection texture view light Matrix.
  49523. */
  49524. SpotLight.prototype._setPosition = function (value) {
  49525. _super.prototype._setPosition.call(this, value);
  49526. this._projectionTextureViewLightDirty = true;
  49527. };
  49528. /**
  49529. * 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.
  49530. * Returns the SpotLight.
  49531. */
  49532. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49533. var activeCamera = this.getScene().activeCamera;
  49534. if (!activeCamera) {
  49535. return;
  49536. }
  49537. this._shadowAngleScale = this._shadowAngleScale || 1;
  49538. var angle = this._shadowAngleScale * this._angle;
  49539. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49540. };
  49541. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49542. this._projectionTextureViewLightDirty = false;
  49543. this._projectionTextureDirty = true;
  49544. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49545. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49546. };
  49547. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49548. this._projectionTextureProjectionLightDirty = false;
  49549. this._projectionTextureDirty = true;
  49550. var light_far = this.projectionTextureLightFar;
  49551. var light_near = this.projectionTextureLightNear;
  49552. var P = light_far / (light_far - light_near);
  49553. var Q = -P * light_near;
  49554. var S = 1.0 / Math.tan(this._angle / 2.0);
  49555. var A = 1.0;
  49556. 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);
  49557. };
  49558. /**
  49559. * Main function for light texture projection matrix computing.
  49560. */
  49561. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49562. this._projectionTextureDirty = false;
  49563. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49564. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49565. };
  49566. SpotLight.prototype._buildUniformLayout = function () {
  49567. this._uniformBuffer.addUniform("vLightData", 4);
  49568. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49569. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49570. this._uniformBuffer.addUniform("vLightDirection", 3);
  49571. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49572. this._uniformBuffer.addUniform("depthValues", 2);
  49573. this._uniformBuffer.create();
  49574. };
  49575. /**
  49576. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49577. * @param effect The effect to update
  49578. * @param lightIndex The index of the light in the effect to update
  49579. * @returns The spot light
  49580. */
  49581. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49582. var normalizeDirection;
  49583. if (this.computeTransformedInformation()) {
  49584. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49585. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49586. }
  49587. else {
  49588. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49589. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49590. }
  49591. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49592. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49593. if (this._projectionTextureViewLightDirty) {
  49594. this._computeProjectionTextureViewLightMatrix();
  49595. }
  49596. if (this._projectionTextureProjectionLightDirty) {
  49597. this._computeProjectionTextureProjectionLightMatrix();
  49598. }
  49599. if (this._projectionTextureDirty) {
  49600. this._computeProjectionTextureMatrix();
  49601. }
  49602. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49603. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49604. }
  49605. return this;
  49606. };
  49607. /**
  49608. * Disposes the light and the associated resources.
  49609. */
  49610. SpotLight.prototype.dispose = function () {
  49611. _super.prototype.dispose.call(this);
  49612. if (this._projectionTexture) {
  49613. this._projectionTexture.dispose();
  49614. }
  49615. };
  49616. __decorate([
  49617. BABYLON.serialize()
  49618. ], SpotLight.prototype, "angle", null);
  49619. __decorate([
  49620. BABYLON.serialize()
  49621. ], SpotLight.prototype, "shadowAngleScale", null);
  49622. __decorate([
  49623. BABYLON.serialize()
  49624. ], SpotLight.prototype, "exponent", void 0);
  49625. __decorate([
  49626. BABYLON.serialize()
  49627. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49628. __decorate([
  49629. BABYLON.serialize()
  49630. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49631. __decorate([
  49632. BABYLON.serialize()
  49633. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49634. __decorate([
  49635. BABYLON.serializeAsTexture("projectedLightTexture")
  49636. ], SpotLight.prototype, "_projectionTexture", void 0);
  49637. return SpotLight;
  49638. }(BABYLON.ShadowLight));
  49639. BABYLON.SpotLight = SpotLight;
  49640. })(BABYLON || (BABYLON = {}));
  49641. //# sourceMappingURL=babylon.spotLight.js.map
  49642. var BABYLON;
  49643. (function (BABYLON) {
  49644. /**
  49645. * Class used to override all child animations of a given target
  49646. */
  49647. var AnimationPropertiesOverride = /** @class */ (function () {
  49648. function AnimationPropertiesOverride() {
  49649. /**
  49650. * Gets or sets a value indicating if animation blending must be used
  49651. */
  49652. this.enableBlending = false;
  49653. /**
  49654. * Gets or sets the blending speed to use when enableBlending is true
  49655. */
  49656. this.blendingSpeed = 0.01;
  49657. /**
  49658. * Gets or sets the default loop mode to use
  49659. */
  49660. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49661. }
  49662. return AnimationPropertiesOverride;
  49663. }());
  49664. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49665. })(BABYLON || (BABYLON = {}));
  49666. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49667. var BABYLON;
  49668. (function (BABYLON) {
  49669. /**
  49670. * Represents the range of an animation
  49671. */
  49672. var AnimationRange = /** @class */ (function () {
  49673. /**
  49674. * Initializes the range of an animation
  49675. * @param name The name of the animation range
  49676. * @param from The starting frame of the animation
  49677. * @param to The ending frame of the animation
  49678. */
  49679. function AnimationRange(
  49680. /**The name of the animation range**/
  49681. name,
  49682. /**The starting frame of the animation */
  49683. from,
  49684. /**The ending frame of the animation*/
  49685. to) {
  49686. this.name = name;
  49687. this.from = from;
  49688. this.to = to;
  49689. }
  49690. /**
  49691. * Makes a copy of the animation range
  49692. * @returns A copy of the animation range
  49693. */
  49694. AnimationRange.prototype.clone = function () {
  49695. return new AnimationRange(this.name, this.from, this.to);
  49696. };
  49697. return AnimationRange;
  49698. }());
  49699. BABYLON.AnimationRange = AnimationRange;
  49700. /**
  49701. * Composed of a frame, and an action function
  49702. */
  49703. var AnimationEvent = /** @class */ (function () {
  49704. /**
  49705. * Initializes the animation event
  49706. * @param frame The frame for which the event is triggered
  49707. * @param action The event to perform when triggered
  49708. * @param onlyOnce Specifies if the event should be triggered only once
  49709. */
  49710. function AnimationEvent(
  49711. /** The frame for which the event is triggered **/
  49712. frame,
  49713. /** The event to perform when triggered **/
  49714. action,
  49715. /** Specifies if the event should be triggered only once**/
  49716. onlyOnce) {
  49717. this.frame = frame;
  49718. this.action = action;
  49719. this.onlyOnce = onlyOnce;
  49720. /**
  49721. * Specifies if the animation event is done
  49722. */
  49723. this.isDone = false;
  49724. }
  49725. return AnimationEvent;
  49726. }());
  49727. BABYLON.AnimationEvent = AnimationEvent;
  49728. /**
  49729. * A cursor which tracks a point on a path
  49730. */
  49731. var PathCursor = /** @class */ (function () {
  49732. /**
  49733. * Initializes the path cursor
  49734. * @param path The path to track
  49735. */
  49736. function PathCursor(path) {
  49737. this.path = path;
  49738. /**
  49739. * Stores path cursor callbacks for when an onchange event is triggered
  49740. */
  49741. this._onchange = new Array();
  49742. /**
  49743. * The value of the path cursor
  49744. */
  49745. this.value = 0;
  49746. /**
  49747. * The animation array of the path cursor
  49748. */
  49749. this.animations = new Array();
  49750. }
  49751. /**
  49752. * Gets the cursor point on the path
  49753. * @returns A point on the path cursor at the cursor location
  49754. */
  49755. PathCursor.prototype.getPoint = function () {
  49756. var point = this.path.getPointAtLengthPosition(this.value);
  49757. return new BABYLON.Vector3(point.x, 0, point.y);
  49758. };
  49759. /**
  49760. * Moves the cursor ahead by the step amount
  49761. * @param step The amount to move the cursor forward
  49762. * @returns This path cursor
  49763. */
  49764. PathCursor.prototype.moveAhead = function (step) {
  49765. if (step === void 0) { step = 0.002; }
  49766. this.move(step);
  49767. return this;
  49768. };
  49769. /**
  49770. * Moves the cursor behind by the step amount
  49771. * @param step The amount to move the cursor back
  49772. * @returns This path cursor
  49773. */
  49774. PathCursor.prototype.moveBack = function (step) {
  49775. if (step === void 0) { step = 0.002; }
  49776. this.move(-step);
  49777. return this;
  49778. };
  49779. /**
  49780. * Moves the cursor by the step amount
  49781. * If the step amount is greater than one, an exception is thrown
  49782. * @param step The amount to move the cursor
  49783. * @returns This path cursor
  49784. */
  49785. PathCursor.prototype.move = function (step) {
  49786. if (Math.abs(step) > 1) {
  49787. throw "step size should be less than 1.";
  49788. }
  49789. this.value += step;
  49790. this.ensureLimits();
  49791. this.raiseOnChange();
  49792. return this;
  49793. };
  49794. /**
  49795. * Ensures that the value is limited between zero and one
  49796. * @returns This path cursor
  49797. */
  49798. PathCursor.prototype.ensureLimits = function () {
  49799. while (this.value > 1) {
  49800. this.value -= 1;
  49801. }
  49802. while (this.value < 0) {
  49803. this.value += 1;
  49804. }
  49805. return this;
  49806. };
  49807. /**
  49808. * Runs onchange callbacks on change (used by the animation engine)
  49809. * @returns This path cursor
  49810. */
  49811. PathCursor.prototype.raiseOnChange = function () {
  49812. var _this = this;
  49813. this._onchange.forEach(function (f) { return f(_this); });
  49814. return this;
  49815. };
  49816. /**
  49817. * Executes a function on change
  49818. * @param f A path cursor onchange callback
  49819. * @returns This path cursor
  49820. */
  49821. PathCursor.prototype.onchange = function (f) {
  49822. this._onchange.push(f);
  49823. return this;
  49824. };
  49825. return PathCursor;
  49826. }());
  49827. BABYLON.PathCursor = PathCursor;
  49828. /**
  49829. * Enum for the animation key frame interpolation type
  49830. */
  49831. var AnimationKeyInterpolation;
  49832. (function (AnimationKeyInterpolation) {
  49833. /**
  49834. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49835. */
  49836. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49837. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49838. /**
  49839. * Class used to store any kind of animation
  49840. */
  49841. var Animation = /** @class */ (function () {
  49842. /**
  49843. * Initializes the animation
  49844. * @param name Name of the animation
  49845. * @param targetProperty Property to animate
  49846. * @param framePerSecond The frames per second of the animation
  49847. * @param dataType The data type of the animation
  49848. * @param loopMode The loop mode of the animation
  49849. * @param enableBlendings Specifies if blending should be enabled
  49850. */
  49851. function Animation(
  49852. /**Name of the animation */
  49853. name,
  49854. /**Property to animate */
  49855. targetProperty,
  49856. /**The frames per second of the animation */
  49857. framePerSecond,
  49858. /**The data type of the animation */
  49859. dataType,
  49860. /**The loop mode of the animation */
  49861. loopMode,
  49862. /**Specifies if blending should be enabled */
  49863. enableBlending) {
  49864. this.name = name;
  49865. this.targetProperty = targetProperty;
  49866. this.framePerSecond = framePerSecond;
  49867. this.dataType = dataType;
  49868. this.loopMode = loopMode;
  49869. this.enableBlending = enableBlending;
  49870. /**
  49871. * @ignore Internal use only
  49872. */
  49873. this._runtimeAnimations = new Array();
  49874. /**
  49875. * The set of event that will be linked to this animation
  49876. */
  49877. this._events = new Array();
  49878. /**
  49879. * Stores the blending speed of the animation
  49880. */
  49881. this.blendingSpeed = 0.01;
  49882. /**
  49883. * Stores the animation ranges for the animation
  49884. */
  49885. this._ranges = {};
  49886. this.targetPropertyPath = targetProperty.split(".");
  49887. this.dataType = dataType;
  49888. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49889. }
  49890. /**
  49891. * @ignore Internal use
  49892. */
  49893. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49894. var dataType = undefined;
  49895. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49896. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49897. }
  49898. else if (from instanceof BABYLON.Quaternion) {
  49899. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49900. }
  49901. else if (from instanceof BABYLON.Vector3) {
  49902. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49903. }
  49904. else if (from instanceof BABYLON.Vector2) {
  49905. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49906. }
  49907. else if (from instanceof BABYLON.Color3) {
  49908. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49909. }
  49910. else if (from instanceof BABYLON.Size) {
  49911. dataType = Animation.ANIMATIONTYPE_SIZE;
  49912. }
  49913. if (dataType == undefined) {
  49914. return null;
  49915. }
  49916. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49917. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49918. animation.setKeys(keys);
  49919. if (easingFunction !== undefined) {
  49920. animation.setEasingFunction(easingFunction);
  49921. }
  49922. return animation;
  49923. };
  49924. /**
  49925. * Sets up an animation
  49926. * @param property The property to animate
  49927. * @param animationType The animation type to apply
  49928. * @param framePerSecond The frames per second of the animation
  49929. * @param easingFunction The easing function used in the animation
  49930. * @returns The created animation
  49931. */
  49932. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49933. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49934. animation.setEasingFunction(easingFunction);
  49935. return animation;
  49936. };
  49937. /**
  49938. * Create and start an animation on a node
  49939. * @param name defines the name of the global animation that will be run on all nodes
  49940. * @param node defines the root node where the animation will take place
  49941. * @param targetProperty defines property to animate
  49942. * @param framePerSecond defines the number of frame per second yo use
  49943. * @param totalFrame defines the number of frames in total
  49944. * @param from defines the initial value
  49945. * @param to defines the final value
  49946. * @param loopMode defines which loop mode you want to use (off by default)
  49947. * @param easingFunction defines the easing function to use (linear by default)
  49948. * @param onAnimationEnd defines the callback to call when animation end
  49949. * @returns the animatable created for this animation
  49950. */
  49951. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49952. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49953. if (!animation) {
  49954. return null;
  49955. }
  49956. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49957. };
  49958. /**
  49959. * Create and start an animation on a node and its descendants
  49960. * @param name defines the name of the global animation that will be run on all nodes
  49961. * @param node defines the root node where the animation will take place
  49962. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49963. * @param targetProperty defines property to animate
  49964. * @param framePerSecond defines the number of frame per second to use
  49965. * @param totalFrame defines the number of frames in total
  49966. * @param from defines the initial value
  49967. * @param to defines the final value
  49968. * @param loopMode defines which loop mode you want to use (off by default)
  49969. * @param easingFunction defines the easing function to use (linear by default)
  49970. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49971. * @returns the list of animatables created for all nodes
  49972. * @example https://www.babylonjs-playground.com/#MH0VLI
  49973. */
  49974. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49975. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49976. if (!animation) {
  49977. return null;
  49978. }
  49979. var scene = node.getScene();
  49980. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49981. };
  49982. /**
  49983. * Creates a new animation, merges it with the existing animations and starts it
  49984. * @param name Name of the animation
  49985. * @param node Node which contains the scene that begins the animations
  49986. * @param targetProperty Specifies which property to animate
  49987. * @param framePerSecond The frames per second of the animation
  49988. * @param totalFrame The total number of frames
  49989. * @param from The frame at the beginning of the animation
  49990. * @param to The frame at the end of the animation
  49991. * @param loopMode Specifies the loop mode of the animation
  49992. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49993. * @param onAnimationEnd Callback to run once the animation is complete
  49994. * @returns Nullable animation
  49995. */
  49996. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49997. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49998. if (!animation) {
  49999. return null;
  50000. }
  50001. node.animations.push(animation);
  50002. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50003. };
  50004. /**
  50005. * Transition property of the Camera to the target Value
  50006. * @param property The property to transition
  50007. * @param targetValue The target Value of the property
  50008. * @param host The object where the property to animate belongs
  50009. * @param scene Scene used to run the animation
  50010. * @param frameRate Framerate (in frame/s) to use
  50011. * @param transition The transition type we want to use
  50012. * @param duration The duration of the animation, in milliseconds
  50013. * @param onAnimationEnd Callback trigger at the end of the animation
  50014. * @returns Nullable animation
  50015. */
  50016. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50017. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50018. if (duration <= 0) {
  50019. host[property] = targetValue;
  50020. if (onAnimationEnd) {
  50021. onAnimationEnd();
  50022. }
  50023. return null;
  50024. }
  50025. var endFrame = frameRate * (duration / 1000);
  50026. transition.setKeys([{
  50027. frame: 0,
  50028. value: host[property].clone ? host[property].clone() : host[property]
  50029. },
  50030. {
  50031. frame: endFrame,
  50032. value: targetValue
  50033. }]);
  50034. if (!host.animations) {
  50035. host.animations = [];
  50036. }
  50037. host.animations.push(transition);
  50038. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50039. animation.onAnimationEnd = onAnimationEnd;
  50040. return animation;
  50041. };
  50042. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50043. /**
  50044. * Return the array of runtime animations currently using this animation
  50045. */
  50046. get: function () {
  50047. return this._runtimeAnimations;
  50048. },
  50049. enumerable: true,
  50050. configurable: true
  50051. });
  50052. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50053. /**
  50054. * Specifies if any of the runtime animations are currently running
  50055. */
  50056. get: function () {
  50057. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50058. var runtimeAnimation = _a[_i];
  50059. if (!runtimeAnimation.isStopped) {
  50060. return true;
  50061. }
  50062. }
  50063. return false;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. // Methods
  50069. /**
  50070. * Converts the animation to a string
  50071. * @param fullDetails support for multiple levels of logging within scene loading
  50072. * @returns String form of the animation
  50073. */
  50074. Animation.prototype.toString = function (fullDetails) {
  50075. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50076. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50077. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50078. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50079. if (fullDetails) {
  50080. ret += ", Ranges: {";
  50081. var first = true;
  50082. for (var name in this._ranges) {
  50083. if (first) {
  50084. ret += ", ";
  50085. first = false;
  50086. }
  50087. ret += name;
  50088. }
  50089. ret += "}";
  50090. }
  50091. return ret;
  50092. };
  50093. /**
  50094. * Add an event to this animation
  50095. * @param event Event to add
  50096. */
  50097. Animation.prototype.addEvent = function (event) {
  50098. this._events.push(event);
  50099. };
  50100. /**
  50101. * Remove all events found at the given frame
  50102. * @param frame The frame to remove events from
  50103. */
  50104. Animation.prototype.removeEvents = function (frame) {
  50105. for (var index = 0; index < this._events.length; index++) {
  50106. if (this._events[index].frame === frame) {
  50107. this._events.splice(index, 1);
  50108. index--;
  50109. }
  50110. }
  50111. };
  50112. /**
  50113. * Retrieves all the events from the animation
  50114. * @returns Events from the animation
  50115. */
  50116. Animation.prototype.getEvents = function () {
  50117. return this._events;
  50118. };
  50119. /**
  50120. * Creates an animation range
  50121. * @param name Name of the animation range
  50122. * @param from Starting frame of the animation range
  50123. * @param to Ending frame of the animation
  50124. */
  50125. Animation.prototype.createRange = function (name, from, to) {
  50126. // check name not already in use; could happen for bones after serialized
  50127. if (!this._ranges[name]) {
  50128. this._ranges[name] = new AnimationRange(name, from, to);
  50129. }
  50130. };
  50131. /**
  50132. * Deletes an animation range by name
  50133. * @param name Name of the animation range to delete
  50134. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50135. */
  50136. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50137. if (deleteFrames === void 0) { deleteFrames = true; }
  50138. var range = this._ranges[name];
  50139. if (!range) {
  50140. return;
  50141. }
  50142. if (deleteFrames) {
  50143. var from = range.from;
  50144. var to = range.to;
  50145. // this loop MUST go high to low for multiple splices to work
  50146. for (var key = this._keys.length - 1; key >= 0; key--) {
  50147. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50148. this._keys.splice(key, 1);
  50149. }
  50150. }
  50151. }
  50152. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50153. };
  50154. /**
  50155. * Gets the animation range by name, or null if not defined
  50156. * @param name Name of the animation range
  50157. * @returns Nullable animation range
  50158. */
  50159. Animation.prototype.getRange = function (name) {
  50160. return this._ranges[name];
  50161. };
  50162. /**
  50163. * Gets the key frames from the animation
  50164. * @returns The key frames of the animation
  50165. */
  50166. Animation.prototype.getKeys = function () {
  50167. return this._keys;
  50168. };
  50169. /**
  50170. * Gets the highest frame rate of the animation
  50171. * @returns Highest frame rate of the animation
  50172. */
  50173. Animation.prototype.getHighestFrame = function () {
  50174. var ret = 0;
  50175. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50176. if (ret < this._keys[key].frame) {
  50177. ret = this._keys[key].frame;
  50178. }
  50179. }
  50180. return ret;
  50181. };
  50182. /**
  50183. * Gets the easing function of the animation
  50184. * @returns Easing function of the animation
  50185. */
  50186. Animation.prototype.getEasingFunction = function () {
  50187. return this._easingFunction;
  50188. };
  50189. /**
  50190. * Sets the easing function of the animation
  50191. * @param easingFunction A custom mathematical formula for animation
  50192. */
  50193. Animation.prototype.setEasingFunction = function (easingFunction) {
  50194. this._easingFunction = easingFunction;
  50195. };
  50196. /**
  50197. * Interpolates a scalar linearly
  50198. * @param startValue Start value of the animation curve
  50199. * @param endValue End value of the animation curve
  50200. * @param gradient Scalar amount to interpolate
  50201. * @returns Interpolated scalar value
  50202. */
  50203. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50204. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50205. };
  50206. /**
  50207. * Interpolates a scalar cubically
  50208. * @param startValue Start value of the animation curve
  50209. * @param outTangent End tangent of the animation
  50210. * @param endValue End value of the animation curve
  50211. * @param inTangent Start tangent of the animation curve
  50212. * @param gradient Scalar amount to interpolate
  50213. * @returns Interpolated scalar value
  50214. */
  50215. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50216. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50217. };
  50218. /**
  50219. * Interpolates a quaternion using a spherical linear interpolation
  50220. * @param startValue Start value of the animation curve
  50221. * @param endValue End value of the animation curve
  50222. * @param gradient Scalar amount to interpolate
  50223. * @returns Interpolated quaternion value
  50224. */
  50225. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50226. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50227. };
  50228. /**
  50229. * Interpolates a quaternion cubically
  50230. * @param startValue Start value of the animation curve
  50231. * @param outTangent End tangent of the animation curve
  50232. * @param endValue End value of the animation curve
  50233. * @param inTangent Start tangent of the animation curve
  50234. * @param gradient Scalar amount to interpolate
  50235. * @returns Interpolated quaternion value
  50236. */
  50237. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50238. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50239. };
  50240. /**
  50241. * Interpolates a Vector3 linearl
  50242. * @param startValue Start value of the animation curve
  50243. * @param endValue End value of the animation curve
  50244. * @param gradient Scalar amount to interpolate
  50245. * @returns Interpolated scalar value
  50246. */
  50247. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50248. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50249. };
  50250. /**
  50251. * Interpolates a Vector3 cubically
  50252. * @param startValue Start value of the animation curve
  50253. * @param outTangent End tangent of the animation
  50254. * @param endValue End value of the animation curve
  50255. * @param inTangent Start tangent of the animation curve
  50256. * @param gradient Scalar amount to interpolate
  50257. * @returns InterpolatedVector3 value
  50258. */
  50259. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50260. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50261. };
  50262. /**
  50263. * Interpolates a Vector2 linearly
  50264. * @param startValue Start value of the animation curve
  50265. * @param endValue End value of the animation curve
  50266. * @param gradient Scalar amount to interpolate
  50267. * @returns Interpolated Vector2 value
  50268. */
  50269. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50270. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50271. };
  50272. /**
  50273. * Interpolates a Vector2 cubically
  50274. * @param startValue Start value of the animation curve
  50275. * @param outTangent End tangent of the animation
  50276. * @param endValue End value of the animation curve
  50277. * @param inTangent Start tangent of the animation curve
  50278. * @param gradient Scalar amount to interpolate
  50279. * @returns Interpolated Vector2 value
  50280. */
  50281. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50282. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50283. };
  50284. /**
  50285. * Interpolates a size linearly
  50286. * @param startValue Start value of the animation curve
  50287. * @param endValue End value of the animation curve
  50288. * @param gradient Scalar amount to interpolate
  50289. * @returns Interpolated Size value
  50290. */
  50291. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50292. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50293. };
  50294. /**
  50295. * Interpolates a Color3 linearly
  50296. * @param startValue Start value of the animation curve
  50297. * @param endValue End value of the animation curve
  50298. * @param gradient Scalar amount to interpolate
  50299. * @returns Interpolated Color3 value
  50300. */
  50301. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50302. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50303. };
  50304. /**
  50305. * @ignore Internal use only
  50306. */
  50307. Animation.prototype._getKeyValue = function (value) {
  50308. if (typeof value === "function") {
  50309. return value();
  50310. }
  50311. return value;
  50312. };
  50313. /**
  50314. * @ignore Internal use only
  50315. */
  50316. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50317. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50318. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50319. }
  50320. var keys = this.getKeys();
  50321. // Try to get a hash to find the right key
  50322. 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));
  50323. if (keys[startKeyIndex].frame >= currentFrame) {
  50324. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50325. startKeyIndex--;
  50326. }
  50327. }
  50328. for (var key = startKeyIndex; key < keys.length; key++) {
  50329. var endKey = keys[key + 1];
  50330. if (endKey.frame >= currentFrame) {
  50331. var startKey = keys[key];
  50332. var startValue = this._getKeyValue(startKey.value);
  50333. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50334. return startValue;
  50335. }
  50336. var endValue = this._getKeyValue(endKey.value);
  50337. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50338. var frameDelta = endKey.frame - startKey.frame;
  50339. // gradient : percent of currentFrame between the frame inf and the frame sup
  50340. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50341. // check for easingFunction and correction of gradient
  50342. var easingFunction = this.getEasingFunction();
  50343. if (easingFunction != null) {
  50344. gradient = easingFunction.ease(gradient);
  50345. }
  50346. switch (this.dataType) {
  50347. // Float
  50348. case Animation.ANIMATIONTYPE_FLOAT:
  50349. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50350. switch (loopMode) {
  50351. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50352. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50353. return floatValue;
  50354. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50355. return offsetValue * repeatCount + floatValue;
  50356. }
  50357. break;
  50358. // Quaternion
  50359. case Animation.ANIMATIONTYPE_QUATERNION:
  50360. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50361. switch (loopMode) {
  50362. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50363. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50364. return quatValue;
  50365. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50366. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50367. }
  50368. return quatValue;
  50369. // Vector3
  50370. case Animation.ANIMATIONTYPE_VECTOR3:
  50371. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50372. switch (loopMode) {
  50373. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50374. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50375. return vec3Value;
  50376. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50377. return vec3Value.add(offsetValue.scale(repeatCount));
  50378. }
  50379. // Vector2
  50380. case Animation.ANIMATIONTYPE_VECTOR2:
  50381. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50382. switch (loopMode) {
  50383. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50384. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50385. return vec2Value;
  50386. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50387. return vec2Value.add(offsetValue.scale(repeatCount));
  50388. }
  50389. // Size
  50390. case Animation.ANIMATIONTYPE_SIZE:
  50391. switch (loopMode) {
  50392. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50393. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50394. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50395. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50396. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50397. }
  50398. // Color3
  50399. case Animation.ANIMATIONTYPE_COLOR3:
  50400. switch (loopMode) {
  50401. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50402. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50403. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50404. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50405. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50406. }
  50407. // Matrix
  50408. case Animation.ANIMATIONTYPE_MATRIX:
  50409. switch (loopMode) {
  50410. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50411. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50412. if (Animation.AllowMatricesInterpolation) {
  50413. workValue = this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50414. return workValue;
  50415. }
  50416. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50417. return startValue;
  50418. }
  50419. default:
  50420. break;
  50421. }
  50422. break;
  50423. }
  50424. }
  50425. return this._getKeyValue(keys[keys.length - 1].value);
  50426. };
  50427. /**
  50428. * Defines the function to use to interpolate matrices
  50429. * @param startValue defines the start matrix
  50430. * @param endValue defines the end matrix
  50431. * @param gradient defines the gradient between both matrices
  50432. * @param result defines an optional target matrix where to store the interpolation
  50433. * @returns the interpolated matrix
  50434. */
  50435. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50436. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50437. if (result) {
  50438. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50439. return result;
  50440. }
  50441. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50442. }
  50443. if (result) {
  50444. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50445. return result;
  50446. }
  50447. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50448. };
  50449. /**
  50450. * Makes a copy of the animation
  50451. * @returns Cloned animation
  50452. */
  50453. Animation.prototype.clone = function () {
  50454. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50455. clone.enableBlending = this.enableBlending;
  50456. clone.blendingSpeed = this.blendingSpeed;
  50457. if (this._keys) {
  50458. clone.setKeys(this._keys);
  50459. }
  50460. if (this._ranges) {
  50461. clone._ranges = {};
  50462. for (var name in this._ranges) {
  50463. var range = this._ranges[name];
  50464. if (!range) {
  50465. continue;
  50466. }
  50467. clone._ranges[name] = range.clone();
  50468. }
  50469. }
  50470. return clone;
  50471. };
  50472. /**
  50473. * Sets the key frames of the animation
  50474. * @param values The animation key frames to set
  50475. */
  50476. Animation.prototype.setKeys = function (values) {
  50477. this._keys = values.slice(0);
  50478. };
  50479. /**
  50480. * Serializes the animation to an object
  50481. * @returns Serialized object
  50482. */
  50483. Animation.prototype.serialize = function () {
  50484. var serializationObject = {};
  50485. serializationObject.name = this.name;
  50486. serializationObject.property = this.targetProperty;
  50487. serializationObject.framePerSecond = this.framePerSecond;
  50488. serializationObject.dataType = this.dataType;
  50489. serializationObject.loopBehavior = this.loopMode;
  50490. serializationObject.enableBlending = this.enableBlending;
  50491. serializationObject.blendingSpeed = this.blendingSpeed;
  50492. var dataType = this.dataType;
  50493. serializationObject.keys = [];
  50494. var keys = this.getKeys();
  50495. for (var index = 0; index < keys.length; index++) {
  50496. var animationKey = keys[index];
  50497. var key = {};
  50498. key.frame = animationKey.frame;
  50499. switch (dataType) {
  50500. case Animation.ANIMATIONTYPE_FLOAT:
  50501. key.values = [animationKey.value];
  50502. break;
  50503. case Animation.ANIMATIONTYPE_QUATERNION:
  50504. case Animation.ANIMATIONTYPE_MATRIX:
  50505. case Animation.ANIMATIONTYPE_VECTOR3:
  50506. case Animation.ANIMATIONTYPE_COLOR3:
  50507. key.values = animationKey.value.asArray();
  50508. break;
  50509. }
  50510. serializationObject.keys.push(key);
  50511. }
  50512. serializationObject.ranges = [];
  50513. for (var name in this._ranges) {
  50514. var source = this._ranges[name];
  50515. if (!source) {
  50516. continue;
  50517. }
  50518. var range = {};
  50519. range.name = name;
  50520. range.from = source.from;
  50521. range.to = source.to;
  50522. serializationObject.ranges.push(range);
  50523. }
  50524. return serializationObject;
  50525. };
  50526. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50527. /**
  50528. * Get the float animation type
  50529. */
  50530. get: function () {
  50531. return Animation._ANIMATIONTYPE_FLOAT;
  50532. },
  50533. enumerable: true,
  50534. configurable: true
  50535. });
  50536. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50537. /**
  50538. * Get the Vector3 animation type
  50539. */
  50540. get: function () {
  50541. return Animation._ANIMATIONTYPE_VECTOR3;
  50542. },
  50543. enumerable: true,
  50544. configurable: true
  50545. });
  50546. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50547. /**
  50548. * Get the Vectpr2 animation type
  50549. */
  50550. get: function () {
  50551. return Animation._ANIMATIONTYPE_VECTOR2;
  50552. },
  50553. enumerable: true,
  50554. configurable: true
  50555. });
  50556. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50557. /**
  50558. * Get the Size animation type
  50559. */
  50560. get: function () {
  50561. return Animation._ANIMATIONTYPE_SIZE;
  50562. },
  50563. enumerable: true,
  50564. configurable: true
  50565. });
  50566. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50567. /**
  50568. * Get the Quaternion animation type
  50569. */
  50570. get: function () {
  50571. return Animation._ANIMATIONTYPE_QUATERNION;
  50572. },
  50573. enumerable: true,
  50574. configurable: true
  50575. });
  50576. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50577. /**
  50578. * Get the Matrix animation type
  50579. */
  50580. get: function () {
  50581. return Animation._ANIMATIONTYPE_MATRIX;
  50582. },
  50583. enumerable: true,
  50584. configurable: true
  50585. });
  50586. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50587. /**
  50588. * Get the Color3 animation type
  50589. */
  50590. get: function () {
  50591. return Animation._ANIMATIONTYPE_COLOR3;
  50592. },
  50593. enumerable: true,
  50594. configurable: true
  50595. });
  50596. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50597. /**
  50598. * Get the Relative Loop Mode
  50599. */
  50600. get: function () {
  50601. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50602. },
  50603. enumerable: true,
  50604. configurable: true
  50605. });
  50606. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50607. /**
  50608. * Get the Cycle Loop Mode
  50609. */
  50610. get: function () {
  50611. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50612. },
  50613. enumerable: true,
  50614. configurable: true
  50615. });
  50616. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50617. /**
  50618. * Get the Constant Loop Mode
  50619. */
  50620. get: function () {
  50621. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50622. },
  50623. enumerable: true,
  50624. configurable: true
  50625. });
  50626. /**
  50627. * Parses an animation object and creates an animation
  50628. * @param parsedAnimation Parsed animation object
  50629. * @returns Animation object
  50630. */
  50631. Animation.Parse = function (parsedAnimation) {
  50632. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50633. var dataType = parsedAnimation.dataType;
  50634. var keys = [];
  50635. var data;
  50636. var index;
  50637. if (parsedAnimation.enableBlending) {
  50638. animation.enableBlending = parsedAnimation.enableBlending;
  50639. }
  50640. if (parsedAnimation.blendingSpeed) {
  50641. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50642. }
  50643. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50644. var key = parsedAnimation.keys[index];
  50645. var inTangent;
  50646. var outTangent;
  50647. switch (dataType) {
  50648. case Animation.ANIMATIONTYPE_FLOAT:
  50649. data = key.values[0];
  50650. if (key.values.length >= 1) {
  50651. inTangent = key.values[1];
  50652. }
  50653. if (key.values.length >= 2) {
  50654. outTangent = key.values[2];
  50655. }
  50656. break;
  50657. case Animation.ANIMATIONTYPE_QUATERNION:
  50658. data = BABYLON.Quaternion.FromArray(key.values);
  50659. if (key.values.length >= 8) {
  50660. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50661. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50662. inTangent = _inTangent;
  50663. }
  50664. }
  50665. if (key.values.length >= 12) {
  50666. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50667. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50668. outTangent = _outTangent;
  50669. }
  50670. }
  50671. break;
  50672. case Animation.ANIMATIONTYPE_MATRIX:
  50673. data = BABYLON.Matrix.FromArray(key.values);
  50674. break;
  50675. case Animation.ANIMATIONTYPE_COLOR3:
  50676. data = BABYLON.Color3.FromArray(key.values);
  50677. break;
  50678. case Animation.ANIMATIONTYPE_VECTOR3:
  50679. default:
  50680. data = BABYLON.Vector3.FromArray(key.values);
  50681. break;
  50682. }
  50683. var keyData = {};
  50684. keyData.frame = key.frame;
  50685. keyData.value = data;
  50686. if (inTangent != undefined) {
  50687. keyData.inTangent = inTangent;
  50688. }
  50689. if (outTangent != undefined) {
  50690. keyData.outTangent = outTangent;
  50691. }
  50692. keys.push(keyData);
  50693. }
  50694. animation.setKeys(keys);
  50695. if (parsedAnimation.ranges) {
  50696. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50697. data = parsedAnimation.ranges[index];
  50698. animation.createRange(data.name, data.from, data.to);
  50699. }
  50700. }
  50701. return animation;
  50702. };
  50703. /**
  50704. * Appends the serialized animations from the source animations
  50705. * @param source Source containing the animations
  50706. * @param destination Target to store the animations
  50707. */
  50708. Animation.AppendSerializedAnimations = function (source, destination) {
  50709. if (source.animations) {
  50710. destination.animations = [];
  50711. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50712. var animation = source.animations[animationIndex];
  50713. destination.animations.push(animation.serialize());
  50714. }
  50715. }
  50716. };
  50717. /**
  50718. * Use matrix interpolation instead of using direct key value when animating matrices
  50719. */
  50720. Animation.AllowMatricesInterpolation = false;
  50721. /**
  50722. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50723. */
  50724. Animation.AllowMatrixDecomposeForInterpolation = true;
  50725. // Statics
  50726. /**
  50727. * Float animation type
  50728. */
  50729. Animation._ANIMATIONTYPE_FLOAT = 0;
  50730. /**
  50731. * Vector3 animation type
  50732. */
  50733. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50734. /**
  50735. * Quaternion animation type
  50736. */
  50737. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50738. /**
  50739. * Matrix animation type
  50740. */
  50741. Animation._ANIMATIONTYPE_MATRIX = 3;
  50742. /**
  50743. * Color3 animation type
  50744. */
  50745. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50746. /**
  50747. * Vector2 animation type
  50748. */
  50749. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50750. /**
  50751. * Size animation type
  50752. */
  50753. Animation._ANIMATIONTYPE_SIZE = 6;
  50754. /**
  50755. * Relative Loop Mode
  50756. */
  50757. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50758. /**
  50759. * Cycle Loop Mode
  50760. */
  50761. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50762. /**
  50763. * Constant Loop Mode
  50764. */
  50765. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50766. return Animation;
  50767. }());
  50768. BABYLON.Animation = Animation;
  50769. })(BABYLON || (BABYLON = {}));
  50770. //# sourceMappingURL=babylon.animation.js.map
  50771. var BABYLON;
  50772. (function (BABYLON) {
  50773. /**
  50774. * This class defines the direct association between an animation and a target
  50775. */
  50776. var TargetedAnimation = /** @class */ (function () {
  50777. function TargetedAnimation() {
  50778. }
  50779. return TargetedAnimation;
  50780. }());
  50781. BABYLON.TargetedAnimation = TargetedAnimation;
  50782. /**
  50783. * Use this class to create coordinated animations on multiple targets
  50784. */
  50785. var AnimationGroup = /** @class */ (function () {
  50786. function AnimationGroup(name, scene) {
  50787. if (scene === void 0) { scene = null; }
  50788. this.name = name;
  50789. this._targetedAnimations = new Array();
  50790. this._animatables = new Array();
  50791. this._from = Number.MAX_VALUE;
  50792. this._to = -Number.MAX_VALUE;
  50793. this._speedRatio = 1;
  50794. this.onAnimationEndObservable = new BABYLON.Observable();
  50795. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50796. this._scene.animationGroups.push(this);
  50797. }
  50798. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50799. /**
  50800. * Define if the animations are started
  50801. */
  50802. get: function () {
  50803. return this._isStarted;
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50809. /**
  50810. * Gets or sets the speed ratio to use for all animations
  50811. */
  50812. get: function () {
  50813. return this._speedRatio;
  50814. },
  50815. /**
  50816. * Gets or sets the speed ratio to use for all animations
  50817. */
  50818. set: function (value) {
  50819. if (this._speedRatio === value) {
  50820. return;
  50821. }
  50822. this._speedRatio = value;
  50823. for (var index = 0; index < this._animatables.length; index++) {
  50824. var animatable = this._animatables[index];
  50825. animatable.speedRatio = this._speedRatio;
  50826. }
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50832. /**
  50833. * Gets the targeted animations for this animation group
  50834. */
  50835. get: function () {
  50836. return this._targetedAnimations;
  50837. },
  50838. enumerable: true,
  50839. configurable: true
  50840. });
  50841. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50842. /**
  50843. * returning the list of animatables controlled by this animation group.
  50844. */
  50845. get: function () {
  50846. return this._animatables;
  50847. },
  50848. enumerable: true,
  50849. configurable: true
  50850. });
  50851. /**
  50852. * Add an animation (with its target) in the group
  50853. * @param animation defines the animation we want to add
  50854. * @param target defines the target of the animation
  50855. * @returns the {BABYLON.TargetedAnimation} object
  50856. */
  50857. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50858. var targetedAnimation = {
  50859. animation: animation,
  50860. target: target
  50861. };
  50862. var keys = animation.getKeys();
  50863. if (this._from > keys[0].frame) {
  50864. this._from = keys[0].frame;
  50865. }
  50866. if (this._to < keys[keys.length - 1].frame) {
  50867. this._to = keys[keys.length - 1].frame;
  50868. }
  50869. this._targetedAnimations.push(targetedAnimation);
  50870. return targetedAnimation;
  50871. };
  50872. /**
  50873. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50874. * It can add constant keys at begin or end
  50875. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50876. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50877. */
  50878. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50879. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50880. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50881. beginFrame = Math.max(beginFrame, this._from);
  50882. endFrame = Math.min(endFrame, this._to);
  50883. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50884. var targetedAnimation = this._targetedAnimations[index];
  50885. var keys = targetedAnimation.animation.getKeys();
  50886. var startKey = keys[0];
  50887. var endKey = keys[keys.length - 1];
  50888. if (startKey.frame > beginFrame) {
  50889. var newKey = {
  50890. frame: beginFrame,
  50891. value: startKey.value,
  50892. inTangent: startKey.inTangent,
  50893. outTangent: startKey.outTangent,
  50894. interpolation: startKey.interpolation
  50895. };
  50896. keys.splice(0, 0, newKey);
  50897. }
  50898. if (endKey.frame < endFrame) {
  50899. var newKey = {
  50900. frame: endFrame,
  50901. value: endKey.value,
  50902. inTangent: endKey.outTangent,
  50903. outTangent: endKey.outTangent,
  50904. interpolation: endKey.interpolation
  50905. };
  50906. keys.push(newKey);
  50907. }
  50908. }
  50909. return this;
  50910. };
  50911. /**
  50912. * Start all animations on given targets
  50913. * @param loop defines if animations must loop
  50914. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50915. * @param from defines the from key (optional)
  50916. * @param to defines the to key (optional)
  50917. * @returns the current animation group
  50918. */
  50919. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50920. var _this = this;
  50921. if (loop === void 0) { loop = false; }
  50922. if (speedRatio === void 0) { speedRatio = 1; }
  50923. if (this._isStarted || this._targetedAnimations.length === 0) {
  50924. return this;
  50925. }
  50926. var _loop_1 = function (targetedAnimation) {
  50927. 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 () {
  50928. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50929. }));
  50930. };
  50931. var this_1 = this;
  50932. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50933. var targetedAnimation = _a[_i];
  50934. _loop_1(targetedAnimation);
  50935. }
  50936. this._speedRatio = speedRatio;
  50937. this._isStarted = true;
  50938. return this;
  50939. };
  50940. /**
  50941. * Pause all animations
  50942. */
  50943. AnimationGroup.prototype.pause = function () {
  50944. if (!this._isStarted) {
  50945. return this;
  50946. }
  50947. for (var index = 0; index < this._animatables.length; index++) {
  50948. var animatable = this._animatables[index];
  50949. animatable.pause();
  50950. }
  50951. return this;
  50952. };
  50953. /**
  50954. * Play all animations to initial state
  50955. * This function will start() the animations if they were not started or will restart() them if they were paused
  50956. * @param loop defines if animations must loop
  50957. */
  50958. AnimationGroup.prototype.play = function (loop) {
  50959. if (this.isStarted) {
  50960. if (loop !== undefined) {
  50961. for (var index = 0; index < this._animatables.length; index++) {
  50962. var animatable = this._animatables[index];
  50963. animatable.loopAnimation = loop;
  50964. }
  50965. }
  50966. this.restart();
  50967. }
  50968. else {
  50969. this.start(loop, this._speedRatio);
  50970. }
  50971. return this;
  50972. };
  50973. /**
  50974. * Reset all animations to initial state
  50975. */
  50976. AnimationGroup.prototype.reset = function () {
  50977. if (!this._isStarted) {
  50978. return this;
  50979. }
  50980. for (var index = 0; index < this._animatables.length; index++) {
  50981. var animatable = this._animatables[index];
  50982. animatable.reset();
  50983. }
  50984. return this;
  50985. };
  50986. /**
  50987. * Restart animations from key 0
  50988. */
  50989. AnimationGroup.prototype.restart = function () {
  50990. if (!this._isStarted) {
  50991. return this;
  50992. }
  50993. for (var index = 0; index < this._animatables.length; index++) {
  50994. var animatable = this._animatables[index];
  50995. animatable.restart();
  50996. }
  50997. return this;
  50998. };
  50999. /**
  51000. * Stop all animations
  51001. */
  51002. AnimationGroup.prototype.stop = function () {
  51003. if (!this._isStarted) {
  51004. return this;
  51005. }
  51006. for (var index = 0; index < this._animatables.length; index++) {
  51007. var animatable = this._animatables[index];
  51008. animatable.stop();
  51009. }
  51010. this._isStarted = false;
  51011. return this;
  51012. };
  51013. /**
  51014. * Set animation weight for all animatables
  51015. * @param weight defines the weight to use
  51016. * @return the animationGroup
  51017. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51018. */
  51019. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51020. for (var index = 0; index < this._animatables.length; index++) {
  51021. var animatable = this._animatables[index];
  51022. animatable.weight = weight;
  51023. }
  51024. return this;
  51025. };
  51026. /**
  51027. * Synchronize and normalize all animatables with a source animatable
  51028. * @param root defines the root animatable to synchronize with
  51029. * @return the animationGroup
  51030. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51031. */
  51032. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51033. for (var index = 0; index < this._animatables.length; index++) {
  51034. var animatable = this._animatables[index];
  51035. animatable.syncWith(root);
  51036. }
  51037. return this;
  51038. };
  51039. /**
  51040. * Goes to a specific frame in this animation group
  51041. * @param frame the frame number to go to
  51042. * @return the animationGroup
  51043. */
  51044. AnimationGroup.prototype.goToFrame = function (frame) {
  51045. if (!this._isStarted) {
  51046. return this;
  51047. }
  51048. for (var index = 0; index < this._animatables.length; index++) {
  51049. var animatable = this._animatables[index];
  51050. animatable.goToFrame(frame);
  51051. }
  51052. return this;
  51053. };
  51054. /**
  51055. * Dispose all associated resources
  51056. */
  51057. AnimationGroup.prototype.dispose = function () {
  51058. this._targetedAnimations = [];
  51059. this._animatables = [];
  51060. var index = this._scene.animationGroups.indexOf(this);
  51061. if (index > -1) {
  51062. this._scene.animationGroups.splice(index, 1);
  51063. }
  51064. };
  51065. return AnimationGroup;
  51066. }());
  51067. BABYLON.AnimationGroup = AnimationGroup;
  51068. })(BABYLON || (BABYLON = {}));
  51069. //# sourceMappingURL=babylon.animationGroup.js.map
  51070. var BABYLON;
  51071. (function (BABYLON) {
  51072. /**
  51073. * Defines a runtime animation
  51074. */
  51075. var RuntimeAnimation = /** @class */ (function () {
  51076. /**
  51077. * Create a new RuntimeAnimation object
  51078. * @param target defines the target of the animation
  51079. * @param animation defines the source animation object
  51080. * @param scene defines the hosting scene
  51081. * @param host defines the initiating Animatable
  51082. */
  51083. function RuntimeAnimation(target, animation, scene, host) {
  51084. /**
  51085. * The current frame of the runtime animation
  51086. */
  51087. this._currentFrame = 0;
  51088. /**
  51089. * The offsets cache of the runtime animation
  51090. */
  51091. this._offsetsCache = {};
  51092. /**
  51093. * The high limits cache of the runtime animation
  51094. */
  51095. this._highLimitsCache = {};
  51096. /**
  51097. * Specifies if the runtime animation has been stopped
  51098. */
  51099. this._stopped = false;
  51100. /**
  51101. * The blending factor of the runtime animation
  51102. */
  51103. this._blendingFactor = 0;
  51104. /**
  51105. * The target path of the runtime animation
  51106. */
  51107. this._targetPath = "";
  51108. /**
  51109. * The weight of the runtime animation
  51110. */
  51111. this._weight = 1.0;
  51112. /**
  51113. * The ratio offset of the runtime animation
  51114. */
  51115. this._ratioOffset = 0;
  51116. /**
  51117. * The previous delay of the runtime animation
  51118. */
  51119. this._previousDelay = 0;
  51120. /**
  51121. * The previous ratio of the runtime animation
  51122. */
  51123. this._previousRatio = 0;
  51124. this._animation = animation;
  51125. this._target = target;
  51126. this._scene = scene;
  51127. this._host = host;
  51128. animation._runtimeAnimations.push(this);
  51129. }
  51130. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51131. /**
  51132. * Gets the current frame of the runtime animation
  51133. */
  51134. get: function () {
  51135. return this._currentFrame;
  51136. },
  51137. enumerable: true,
  51138. configurable: true
  51139. });
  51140. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51141. /**
  51142. * Gets the weight of the runtime animation
  51143. */
  51144. get: function () {
  51145. return this._weight;
  51146. },
  51147. enumerable: true,
  51148. configurable: true
  51149. });
  51150. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51151. /**
  51152. * Gets the original value of the runtime animation
  51153. */
  51154. get: function () {
  51155. return this._originalValue;
  51156. },
  51157. enumerable: true,
  51158. configurable: true
  51159. });
  51160. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51161. /**
  51162. * Gets the current value of the runtime animation
  51163. */
  51164. get: function () {
  51165. return this._currentValue;
  51166. },
  51167. enumerable: true,
  51168. configurable: true
  51169. });
  51170. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51171. /**
  51172. * Gets the target path of the runtime animation
  51173. */
  51174. get: function () {
  51175. return this._targetPath;
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51181. /**
  51182. * Gets the actual target of the runtime animation
  51183. */
  51184. get: function () {
  51185. return this._activeTarget;
  51186. },
  51187. enumerable: true,
  51188. configurable: true
  51189. });
  51190. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51191. /**
  51192. * Gets the animation from the runtime animation
  51193. */
  51194. get: function () {
  51195. return this._animation;
  51196. },
  51197. enumerable: true,
  51198. configurable: true
  51199. });
  51200. /**
  51201. * Resets the runtime animation to the beginning
  51202. */
  51203. RuntimeAnimation.prototype.reset = function () {
  51204. this._offsetsCache = {};
  51205. this._highLimitsCache = {};
  51206. this._currentFrame = 0;
  51207. this._blendingFactor = 0;
  51208. this._originalValue = null;
  51209. };
  51210. /**
  51211. * Specifies if the runtime animation is stopped
  51212. * @returns Boolean specifying if the runtime animation is stopped
  51213. */
  51214. RuntimeAnimation.prototype.isStopped = function () {
  51215. return this._stopped;
  51216. };
  51217. /**
  51218. * Disposes of the runtime animation
  51219. */
  51220. RuntimeAnimation.prototype.dispose = function () {
  51221. var index = this._animation.runtimeAnimations.indexOf(this);
  51222. if (index > -1) {
  51223. this._animation.runtimeAnimations.splice(index, 1);
  51224. }
  51225. };
  51226. /**
  51227. * Interpolates the animation from the current frame
  51228. * @param currentFrame The frame to interpolate the animation to
  51229. * @param repeatCount The number of times that the animation should loop
  51230. * @param loopMode The type of looping mode to use
  51231. * @param offsetValue Animation offset value
  51232. * @param highLimitValue The high limit value
  51233. * @returns The interpolated value
  51234. */
  51235. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51236. this._currentFrame = currentFrame;
  51237. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51238. };
  51239. /**
  51240. * Affect the interpolated value to the target
  51241. * @param currentValue defines the value computed by the animation
  51242. * @param weight defines the weight to apply to this value
  51243. */
  51244. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51245. if (weight === void 0) { weight = 1.0; }
  51246. if (this._target instanceof Array) {
  51247. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51248. var target = _a[_i];
  51249. this._setValue(target, currentValue, weight);
  51250. }
  51251. }
  51252. else {
  51253. this._setValue(this._target, currentValue, weight);
  51254. }
  51255. };
  51256. /**
  51257. * Sets the value of the runtime animation
  51258. * @param target The target property of the runtime animation
  51259. * @param currentValue The current value to use for the runtime animation
  51260. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51261. */
  51262. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51263. if (weight === void 0) { weight = 1.0; }
  51264. // Set value
  51265. var path;
  51266. var destination;
  51267. var targetPropertyPath = this._animation.targetPropertyPath;
  51268. if (targetPropertyPath.length > 1) {
  51269. var property = target[targetPropertyPath[0]];
  51270. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51271. property = property[targetPropertyPath[index]];
  51272. }
  51273. path = targetPropertyPath[targetPropertyPath.length - 1];
  51274. destination = property;
  51275. }
  51276. else {
  51277. path = targetPropertyPath[0];
  51278. destination = target;
  51279. }
  51280. this._targetPath = path;
  51281. this._activeTarget = destination;
  51282. this._weight = weight;
  51283. // Blending
  51284. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51285. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51286. if (enableBlending && this._blendingFactor <= 1.0) {
  51287. if (!this._originalBlendValue) {
  51288. var originalValue = destination[path];
  51289. if (originalValue.clone) {
  51290. this._originalBlendValue = originalValue.clone();
  51291. }
  51292. else {
  51293. this._originalBlendValue = originalValue;
  51294. }
  51295. }
  51296. }
  51297. if (weight !== -1.0) {
  51298. if (!this._originalValue) {
  51299. var originalValue = void 0;
  51300. if (destination.getRestPose) { // For bones
  51301. originalValue = destination.getRestPose();
  51302. }
  51303. else {
  51304. originalValue = destination[path];
  51305. }
  51306. if (originalValue.clone) {
  51307. this._originalValue = originalValue.clone();
  51308. }
  51309. else {
  51310. this._originalValue = originalValue;
  51311. }
  51312. }
  51313. }
  51314. if (enableBlending && this._blendingFactor <= 1.0) {
  51315. if (this._originalBlendValue.m) { // Matrix
  51316. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51317. if (this._currentValue) {
  51318. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51319. }
  51320. else {
  51321. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51322. }
  51323. }
  51324. else {
  51325. if (this._currentValue) {
  51326. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51327. }
  51328. else {
  51329. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51330. }
  51331. }
  51332. }
  51333. else {
  51334. var constructor = this._originalBlendValue.constructor;
  51335. if (constructor.Lerp) { // Lerp supported
  51336. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51337. }
  51338. else if (constructor.Slerp) { // Slerp supported
  51339. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51340. }
  51341. else if (this._originalBlendValue.toFixed) { // Number
  51342. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51343. }
  51344. else { // Blending not supported
  51345. this._currentValue = currentValue;
  51346. }
  51347. }
  51348. this._blendingFactor += blendingSpeed;
  51349. }
  51350. else {
  51351. this._currentValue = currentValue;
  51352. }
  51353. if (weight !== -1.0) {
  51354. this._scene._registerTargetForLateAnimationBinding(this);
  51355. }
  51356. else {
  51357. destination[path] = this._currentValue;
  51358. }
  51359. if (target.markAsDirty) {
  51360. target.markAsDirty(this._animation.targetProperty);
  51361. }
  51362. };
  51363. /**
  51364. * Gets the loop pmode of the runtime animation
  51365. * @returns Loop Mode
  51366. */
  51367. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51368. if (this._target && this._target.animationPropertiesOverride) {
  51369. return this._target.animationPropertiesOverride.loopMode;
  51370. }
  51371. return this._animation.loopMode;
  51372. };
  51373. /**
  51374. * Move the current animation to a given frame
  51375. * @param frame defines the frame to move to
  51376. */
  51377. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51378. var keys = this._animation.getKeys();
  51379. if (frame < keys[0].frame) {
  51380. frame = keys[0].frame;
  51381. }
  51382. else if (frame > keys[keys.length - 1].frame) {
  51383. frame = keys[keys.length - 1].frame;
  51384. }
  51385. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51386. this.setValue(currentValue, -1);
  51387. };
  51388. /**
  51389. * @ignore Internal use only
  51390. */
  51391. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51392. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51393. this._ratioOffset = this._previousRatio - newRatio;
  51394. };
  51395. /**
  51396. * Execute the current animation
  51397. * @param delay defines the delay to add to the current frame
  51398. * @param from defines the lower bound of the animation range
  51399. * @param to defines the upper bound of the animation range
  51400. * @param loop defines if the current animation must loop
  51401. * @param speedRatio defines the current speed ratio
  51402. * @param weight defines the weight of the animation (default is -1 so no weight)
  51403. * @returns a boolean indicating if the animation has ended
  51404. */
  51405. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51406. if (weight === void 0) { weight = -1.0; }
  51407. var targetPropertyPath = this._animation.targetPropertyPath;
  51408. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51409. this._stopped = true;
  51410. return false;
  51411. }
  51412. var returnValue = true;
  51413. var keys = this._animation.getKeys();
  51414. // Adding a start key at frame 0 if missing
  51415. if (keys[0].frame !== 0) {
  51416. var newKey = { frame: 0, value: keys[0].value };
  51417. keys.splice(0, 0, newKey);
  51418. }
  51419. // Check limits
  51420. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51421. from = keys[0].frame;
  51422. }
  51423. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51424. to = keys[keys.length - 1].frame;
  51425. }
  51426. //to and from cannot be the same key
  51427. if (from === to) {
  51428. if (from > keys[0].frame) {
  51429. from--;
  51430. }
  51431. else if (to < keys[keys.length - 1].frame) {
  51432. to++;
  51433. }
  51434. }
  51435. // Compute ratio
  51436. var range = to - from;
  51437. var offsetValue;
  51438. // ratio represents the frame delta between from and to
  51439. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51440. var highLimitValue = 0;
  51441. this._previousDelay = delay;
  51442. this._previousRatio = ratio;
  51443. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51444. returnValue = false;
  51445. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51446. }
  51447. else {
  51448. // Get max value if required
  51449. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51450. var keyOffset = to.toString() + from.toString();
  51451. if (!this._offsetsCache[keyOffset]) {
  51452. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51453. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51454. switch (this._animation.dataType) {
  51455. // Float
  51456. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51457. this._offsetsCache[keyOffset] = toValue - fromValue;
  51458. break;
  51459. // Quaternion
  51460. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51462. break;
  51463. // Vector3
  51464. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51465. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51466. // Vector2
  51467. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51468. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51469. // Size
  51470. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51471. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51472. // Color3
  51473. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51474. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51475. default:
  51476. break;
  51477. }
  51478. this._highLimitsCache[keyOffset] = toValue;
  51479. }
  51480. highLimitValue = this._highLimitsCache[keyOffset];
  51481. offsetValue = this._offsetsCache[keyOffset];
  51482. }
  51483. }
  51484. if (offsetValue === undefined) {
  51485. switch (this._animation.dataType) {
  51486. // Float
  51487. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51488. offsetValue = 0;
  51489. break;
  51490. // Quaternion
  51491. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51492. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51493. break;
  51494. // Vector3
  51495. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51496. offsetValue = BABYLON.Vector3.Zero();
  51497. break;
  51498. // Vector2
  51499. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51500. offsetValue = BABYLON.Vector2.Zero();
  51501. break;
  51502. // Size
  51503. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51504. offsetValue = BABYLON.Size.Zero();
  51505. break;
  51506. // Color3
  51507. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51508. offsetValue = BABYLON.Color3.Black();
  51509. }
  51510. }
  51511. // Compute value
  51512. var repeatCount = (ratio / range) >> 0;
  51513. var currentFrame = returnValue ? from + ratio % range : to;
  51514. // Need to normalize?
  51515. if (this._host && this._host.syncRoot) {
  51516. var syncRoot = this._host.syncRoot;
  51517. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51518. currentFrame = from + (to - from) * hostNormalizedFrame;
  51519. }
  51520. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51521. // Set value
  51522. this.setValue(currentValue, weight);
  51523. // Check events
  51524. var events = this._animation.getEvents();
  51525. for (var index = 0; index < events.length; index++) {
  51526. // Make sure current frame has passed event frame and that event frame is within the current range
  51527. // Also, handle both forward and reverse animations
  51528. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51529. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51530. var event = events[index];
  51531. if (!event.isDone) {
  51532. // If event should be done only once, remove it.
  51533. if (event.onlyOnce) {
  51534. events.splice(index, 1);
  51535. index--;
  51536. }
  51537. event.isDone = true;
  51538. event.action();
  51539. } // Don't do anything if the event has already be done.
  51540. }
  51541. else if (events[index].isDone && !events[index].onlyOnce) {
  51542. // reset event, the animation is looping
  51543. events[index].isDone = false;
  51544. }
  51545. }
  51546. if (!returnValue) {
  51547. this._stopped = true;
  51548. }
  51549. return returnValue;
  51550. };
  51551. return RuntimeAnimation;
  51552. }());
  51553. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51554. })(BABYLON || (BABYLON = {}));
  51555. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51556. var BABYLON;
  51557. (function (BABYLON) {
  51558. var Animatable = /** @class */ (function () {
  51559. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51560. if (fromFrame === void 0) { fromFrame = 0; }
  51561. if (toFrame === void 0) { toFrame = 100; }
  51562. if (loopAnimation === void 0) { loopAnimation = false; }
  51563. if (speedRatio === void 0) { speedRatio = 1.0; }
  51564. this.target = target;
  51565. this.fromFrame = fromFrame;
  51566. this.toFrame = toFrame;
  51567. this.loopAnimation = loopAnimation;
  51568. this.onAnimationEnd = onAnimationEnd;
  51569. this._localDelayOffset = null;
  51570. this._pausedDelay = null;
  51571. this._runtimeAnimations = new Array();
  51572. this._paused = false;
  51573. this._speedRatio = 1;
  51574. this._weight = -1.0;
  51575. this.animationStarted = false;
  51576. this._scene = scene;
  51577. if (animations) {
  51578. this.appendAnimations(target, animations);
  51579. }
  51580. this._speedRatio = speedRatio;
  51581. scene._activeAnimatables.push(this);
  51582. }
  51583. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51584. /**
  51585. * Gets the root Animatable used to synchronize and normalize animations
  51586. */
  51587. get: function () {
  51588. return this._syncRoot;
  51589. },
  51590. enumerable: true,
  51591. configurable: true
  51592. });
  51593. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51594. /**
  51595. * Gets the current frame of the first RuntimeAnimation
  51596. * Used to synchronize Animatables
  51597. */
  51598. get: function () {
  51599. if (this._runtimeAnimations.length === 0) {
  51600. return 0;
  51601. }
  51602. return this._runtimeAnimations[0].currentFrame;
  51603. },
  51604. enumerable: true,
  51605. configurable: true
  51606. });
  51607. Object.defineProperty(Animatable.prototype, "weight", {
  51608. /**
  51609. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51610. */
  51611. get: function () {
  51612. return this._weight;
  51613. },
  51614. set: function (value) {
  51615. if (value === -1) { // -1 is ok and means no weight
  51616. this._weight = -1;
  51617. return;
  51618. }
  51619. // Else weight must be in [0, 1] range
  51620. this._weight = Math.min(Math.max(value, 0), 1.0);
  51621. },
  51622. enumerable: true,
  51623. configurable: true
  51624. });
  51625. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51626. /**
  51627. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51628. */
  51629. get: function () {
  51630. return this._speedRatio;
  51631. },
  51632. set: function (value) {
  51633. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51634. var animation = this._runtimeAnimations[index];
  51635. animation._prepareForSpeedRatioChange(value);
  51636. }
  51637. this._speedRatio = value;
  51638. },
  51639. enumerable: true,
  51640. configurable: true
  51641. });
  51642. // Methods
  51643. /**
  51644. * Synchronize and normalize current Animatable with a source Animatable
  51645. * This is useful when using animation weights and when animations are not of the same length
  51646. * @param root defines the root Animatable to synchronize with
  51647. * @returns the current Animatable
  51648. */
  51649. Animatable.prototype.syncWith = function (root) {
  51650. this._syncRoot = root;
  51651. if (root) {
  51652. // Make sure this animatable will animate after the root
  51653. var index = this._scene._activeAnimatables.indexOf(this);
  51654. if (index > -1) {
  51655. this._scene._activeAnimatables.splice(index, 1);
  51656. this._scene._activeAnimatables.push(this);
  51657. }
  51658. }
  51659. return this;
  51660. };
  51661. Animatable.prototype.getAnimations = function () {
  51662. return this._runtimeAnimations;
  51663. };
  51664. Animatable.prototype.appendAnimations = function (target, animations) {
  51665. for (var index = 0; index < animations.length; index++) {
  51666. var animation = animations[index];
  51667. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51668. }
  51669. };
  51670. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51671. var runtimeAnimations = this._runtimeAnimations;
  51672. for (var index = 0; index < runtimeAnimations.length; index++) {
  51673. if (runtimeAnimations[index].animation.targetProperty === property) {
  51674. return runtimeAnimations[index].animation;
  51675. }
  51676. }
  51677. return null;
  51678. };
  51679. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51680. var runtimeAnimations = this._runtimeAnimations;
  51681. for (var index = 0; index < runtimeAnimations.length; index++) {
  51682. if (runtimeAnimations[index].animation.targetProperty === property) {
  51683. return runtimeAnimations[index];
  51684. }
  51685. }
  51686. return null;
  51687. };
  51688. Animatable.prototype.reset = function () {
  51689. var runtimeAnimations = this._runtimeAnimations;
  51690. for (var index = 0; index < runtimeAnimations.length; index++) {
  51691. runtimeAnimations[index].reset();
  51692. }
  51693. // Reset to original value
  51694. for (index = 0; index < runtimeAnimations.length; index++) {
  51695. var animation = runtimeAnimations[index];
  51696. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51697. }
  51698. this._localDelayOffset = null;
  51699. this._pausedDelay = null;
  51700. };
  51701. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51702. var runtimeAnimations = this._runtimeAnimations;
  51703. for (var index = 0; index < runtimeAnimations.length; index++) {
  51704. runtimeAnimations[index].animation.enableBlending = true;
  51705. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51706. }
  51707. };
  51708. Animatable.prototype.disableBlending = function () {
  51709. var runtimeAnimations = this._runtimeAnimations;
  51710. for (var index = 0; index < runtimeAnimations.length; index++) {
  51711. runtimeAnimations[index].animation.enableBlending = false;
  51712. }
  51713. };
  51714. Animatable.prototype.goToFrame = function (frame) {
  51715. var runtimeAnimations = this._runtimeAnimations;
  51716. if (runtimeAnimations[0]) {
  51717. var fps = runtimeAnimations[0].animation.framePerSecond;
  51718. var currentFrame = runtimeAnimations[0].currentFrame;
  51719. var adjustTime = frame - currentFrame;
  51720. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51721. if (this._localDelayOffset === null) {
  51722. this._localDelayOffset = 0;
  51723. }
  51724. this._localDelayOffset -= delay;
  51725. }
  51726. for (var index = 0; index < runtimeAnimations.length; index++) {
  51727. runtimeAnimations[index].goToFrame(frame);
  51728. }
  51729. };
  51730. Animatable.prototype.pause = function () {
  51731. if (this._paused) {
  51732. return;
  51733. }
  51734. this._paused = true;
  51735. };
  51736. Animatable.prototype.restart = function () {
  51737. this._paused = false;
  51738. };
  51739. Animatable.prototype.stop = function (animationName) {
  51740. if (animationName) {
  51741. var idx = this._scene._activeAnimatables.indexOf(this);
  51742. if (idx > -1) {
  51743. var runtimeAnimations = this._runtimeAnimations;
  51744. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51745. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51746. continue;
  51747. }
  51748. runtimeAnimations[index].dispose();
  51749. runtimeAnimations.splice(index, 1);
  51750. }
  51751. if (runtimeAnimations.length == 0) {
  51752. this._scene._activeAnimatables.splice(idx, 1);
  51753. if (this.onAnimationEnd) {
  51754. this.onAnimationEnd();
  51755. }
  51756. }
  51757. }
  51758. }
  51759. else {
  51760. var index = this._scene._activeAnimatables.indexOf(this);
  51761. if (index > -1) {
  51762. this._scene._activeAnimatables.splice(index, 1);
  51763. var runtimeAnimations = this._runtimeAnimations;
  51764. for (var index = 0; index < runtimeAnimations.length; index++) {
  51765. runtimeAnimations[index].dispose();
  51766. }
  51767. if (this.onAnimationEnd) {
  51768. this.onAnimationEnd();
  51769. }
  51770. }
  51771. }
  51772. };
  51773. Animatable.prototype._animate = function (delay) {
  51774. if (this._paused) {
  51775. this.animationStarted = false;
  51776. if (this._pausedDelay === null) {
  51777. this._pausedDelay = delay;
  51778. }
  51779. return true;
  51780. }
  51781. if (this._localDelayOffset === null) {
  51782. this._localDelayOffset = delay;
  51783. this._pausedDelay = null;
  51784. }
  51785. else if (this._pausedDelay !== null) {
  51786. this._localDelayOffset += delay - this._pausedDelay;
  51787. this._pausedDelay = null;
  51788. }
  51789. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51790. return true;
  51791. }
  51792. // Animating
  51793. var running = false;
  51794. var runtimeAnimations = this._runtimeAnimations;
  51795. var index;
  51796. for (index = 0; index < runtimeAnimations.length; index++) {
  51797. var animation = runtimeAnimations[index];
  51798. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51799. running = running || isRunning;
  51800. }
  51801. this.animationStarted = running;
  51802. if (!running) {
  51803. // Remove from active animatables
  51804. index = this._scene._activeAnimatables.indexOf(this);
  51805. this._scene._activeAnimatables.splice(index, 1);
  51806. // Dispose all runtime animations
  51807. for (index = 0; index < runtimeAnimations.length; index++) {
  51808. runtimeAnimations[index].dispose();
  51809. }
  51810. }
  51811. if (!running && this.onAnimationEnd) {
  51812. this.onAnimationEnd();
  51813. this.onAnimationEnd = null;
  51814. }
  51815. return running;
  51816. };
  51817. return Animatable;
  51818. }());
  51819. BABYLON.Animatable = Animatable;
  51820. })(BABYLON || (BABYLON = {}));
  51821. //# sourceMappingURL=babylon.animatable.js.map
  51822. var BABYLON;
  51823. (function (BABYLON) {
  51824. var EasingFunction = /** @class */ (function () {
  51825. function EasingFunction() {
  51826. // Properties
  51827. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51828. }
  51829. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51830. get: function () {
  51831. return EasingFunction._EASINGMODE_EASEIN;
  51832. },
  51833. enumerable: true,
  51834. configurable: true
  51835. });
  51836. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51837. get: function () {
  51838. return EasingFunction._EASINGMODE_EASEOUT;
  51839. },
  51840. enumerable: true,
  51841. configurable: true
  51842. });
  51843. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51844. get: function () {
  51845. return EasingFunction._EASINGMODE_EASEINOUT;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51851. var n = Math.min(Math.max(easingMode, 0), 2);
  51852. this._easingMode = n;
  51853. };
  51854. EasingFunction.prototype.getEasingMode = function () {
  51855. return this._easingMode;
  51856. };
  51857. EasingFunction.prototype.easeInCore = function (gradient) {
  51858. throw new Error('You must implement this method');
  51859. };
  51860. EasingFunction.prototype.ease = function (gradient) {
  51861. switch (this._easingMode) {
  51862. case EasingFunction.EASINGMODE_EASEIN:
  51863. return this.easeInCore(gradient);
  51864. case EasingFunction.EASINGMODE_EASEOUT:
  51865. return (1 - this.easeInCore(1 - gradient));
  51866. }
  51867. if (gradient >= 0.5) {
  51868. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51869. }
  51870. return (this.easeInCore(gradient * 2) * 0.5);
  51871. };
  51872. //Statics
  51873. EasingFunction._EASINGMODE_EASEIN = 0;
  51874. EasingFunction._EASINGMODE_EASEOUT = 1;
  51875. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51876. return EasingFunction;
  51877. }());
  51878. BABYLON.EasingFunction = EasingFunction;
  51879. var CircleEase = /** @class */ (function (_super) {
  51880. __extends(CircleEase, _super);
  51881. function CircleEase() {
  51882. return _super !== null && _super.apply(this, arguments) || this;
  51883. }
  51884. CircleEase.prototype.easeInCore = function (gradient) {
  51885. gradient = Math.max(0, Math.min(1, gradient));
  51886. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51887. };
  51888. return CircleEase;
  51889. }(EasingFunction));
  51890. BABYLON.CircleEase = CircleEase;
  51891. var BackEase = /** @class */ (function (_super) {
  51892. __extends(BackEase, _super);
  51893. function BackEase(amplitude) {
  51894. if (amplitude === void 0) { amplitude = 1; }
  51895. var _this = _super.call(this) || this;
  51896. _this.amplitude = amplitude;
  51897. return _this;
  51898. }
  51899. BackEase.prototype.easeInCore = function (gradient) {
  51900. var num = Math.max(0, this.amplitude);
  51901. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51902. };
  51903. return BackEase;
  51904. }(EasingFunction));
  51905. BABYLON.BackEase = BackEase;
  51906. var BounceEase = /** @class */ (function (_super) {
  51907. __extends(BounceEase, _super);
  51908. function BounceEase(bounces, bounciness) {
  51909. if (bounces === void 0) { bounces = 3; }
  51910. if (bounciness === void 0) { bounciness = 2; }
  51911. var _this = _super.call(this) || this;
  51912. _this.bounces = bounces;
  51913. _this.bounciness = bounciness;
  51914. return _this;
  51915. }
  51916. BounceEase.prototype.easeInCore = function (gradient) {
  51917. var y = Math.max(0.0, this.bounces);
  51918. var bounciness = this.bounciness;
  51919. if (bounciness <= 1.0) {
  51920. bounciness = 1.001;
  51921. }
  51922. var num9 = Math.pow(bounciness, y);
  51923. var num5 = 1.0 - bounciness;
  51924. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51925. var num15 = gradient * num4;
  51926. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51927. var num3 = Math.floor(num65);
  51928. var num13 = num3 + 1.0;
  51929. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51930. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51931. var num7 = (num8 + num12) * 0.5;
  51932. var num6 = gradient - num7;
  51933. var num2 = num7 - num8;
  51934. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51935. };
  51936. return BounceEase;
  51937. }(EasingFunction));
  51938. BABYLON.BounceEase = BounceEase;
  51939. var CubicEase = /** @class */ (function (_super) {
  51940. __extends(CubicEase, _super);
  51941. function CubicEase() {
  51942. return _super !== null && _super.apply(this, arguments) || this;
  51943. }
  51944. CubicEase.prototype.easeInCore = function (gradient) {
  51945. return (gradient * gradient * gradient);
  51946. };
  51947. return CubicEase;
  51948. }(EasingFunction));
  51949. BABYLON.CubicEase = CubicEase;
  51950. var ElasticEase = /** @class */ (function (_super) {
  51951. __extends(ElasticEase, _super);
  51952. function ElasticEase(oscillations, springiness) {
  51953. if (oscillations === void 0) { oscillations = 3; }
  51954. if (springiness === void 0) { springiness = 3; }
  51955. var _this = _super.call(this) || this;
  51956. _this.oscillations = oscillations;
  51957. _this.springiness = springiness;
  51958. return _this;
  51959. }
  51960. ElasticEase.prototype.easeInCore = function (gradient) {
  51961. var num2;
  51962. var num3 = Math.max(0.0, this.oscillations);
  51963. var num = Math.max(0.0, this.springiness);
  51964. if (num == 0) {
  51965. num2 = gradient;
  51966. }
  51967. else {
  51968. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51969. }
  51970. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51971. };
  51972. return ElasticEase;
  51973. }(EasingFunction));
  51974. BABYLON.ElasticEase = ElasticEase;
  51975. var ExponentialEase = /** @class */ (function (_super) {
  51976. __extends(ExponentialEase, _super);
  51977. function ExponentialEase(exponent) {
  51978. if (exponent === void 0) { exponent = 2; }
  51979. var _this = _super.call(this) || this;
  51980. _this.exponent = exponent;
  51981. return _this;
  51982. }
  51983. ExponentialEase.prototype.easeInCore = function (gradient) {
  51984. if (this.exponent <= 0) {
  51985. return gradient;
  51986. }
  51987. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51988. };
  51989. return ExponentialEase;
  51990. }(EasingFunction));
  51991. BABYLON.ExponentialEase = ExponentialEase;
  51992. var PowerEase = /** @class */ (function (_super) {
  51993. __extends(PowerEase, _super);
  51994. function PowerEase(power) {
  51995. if (power === void 0) { power = 2; }
  51996. var _this = _super.call(this) || this;
  51997. _this.power = power;
  51998. return _this;
  51999. }
  52000. PowerEase.prototype.easeInCore = function (gradient) {
  52001. var y = Math.max(0.0, this.power);
  52002. return Math.pow(gradient, y);
  52003. };
  52004. return PowerEase;
  52005. }(EasingFunction));
  52006. BABYLON.PowerEase = PowerEase;
  52007. var QuadraticEase = /** @class */ (function (_super) {
  52008. __extends(QuadraticEase, _super);
  52009. function QuadraticEase() {
  52010. return _super !== null && _super.apply(this, arguments) || this;
  52011. }
  52012. QuadraticEase.prototype.easeInCore = function (gradient) {
  52013. return (gradient * gradient);
  52014. };
  52015. return QuadraticEase;
  52016. }(EasingFunction));
  52017. BABYLON.QuadraticEase = QuadraticEase;
  52018. var QuarticEase = /** @class */ (function (_super) {
  52019. __extends(QuarticEase, _super);
  52020. function QuarticEase() {
  52021. return _super !== null && _super.apply(this, arguments) || this;
  52022. }
  52023. QuarticEase.prototype.easeInCore = function (gradient) {
  52024. return (gradient * gradient * gradient * gradient);
  52025. };
  52026. return QuarticEase;
  52027. }(EasingFunction));
  52028. BABYLON.QuarticEase = QuarticEase;
  52029. var QuinticEase = /** @class */ (function (_super) {
  52030. __extends(QuinticEase, _super);
  52031. function QuinticEase() {
  52032. return _super !== null && _super.apply(this, arguments) || this;
  52033. }
  52034. QuinticEase.prototype.easeInCore = function (gradient) {
  52035. return (gradient * gradient * gradient * gradient * gradient);
  52036. };
  52037. return QuinticEase;
  52038. }(EasingFunction));
  52039. BABYLON.QuinticEase = QuinticEase;
  52040. var SineEase = /** @class */ (function (_super) {
  52041. __extends(SineEase, _super);
  52042. function SineEase() {
  52043. return _super !== null && _super.apply(this, arguments) || this;
  52044. }
  52045. SineEase.prototype.easeInCore = function (gradient) {
  52046. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52047. };
  52048. return SineEase;
  52049. }(EasingFunction));
  52050. BABYLON.SineEase = SineEase;
  52051. var BezierCurveEase = /** @class */ (function (_super) {
  52052. __extends(BezierCurveEase, _super);
  52053. function BezierCurveEase(x1, y1, x2, y2) {
  52054. if (x1 === void 0) { x1 = 0; }
  52055. if (y1 === void 0) { y1 = 0; }
  52056. if (x2 === void 0) { x2 = 1; }
  52057. if (y2 === void 0) { y2 = 1; }
  52058. var _this = _super.call(this) || this;
  52059. _this.x1 = x1;
  52060. _this.y1 = y1;
  52061. _this.x2 = x2;
  52062. _this.y2 = y2;
  52063. return _this;
  52064. }
  52065. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52066. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52067. };
  52068. return BezierCurveEase;
  52069. }(EasingFunction));
  52070. BABYLON.BezierCurveEase = BezierCurveEase;
  52071. })(BABYLON || (BABYLON = {}));
  52072. //# sourceMappingURL=babylon.easing.js.map
  52073. var BABYLON;
  52074. (function (BABYLON) {
  52075. /**
  52076. * A Condition applied to an Action
  52077. */
  52078. var Condition = /** @class */ (function () {
  52079. /**
  52080. * Creates a new Condition
  52081. * @param actionManager the manager of the action the condition is applied to
  52082. */
  52083. function Condition(actionManager) {
  52084. this._actionManager = actionManager;
  52085. }
  52086. /**
  52087. * Check if the current condition is valid
  52088. * @returns a boolean
  52089. */
  52090. Condition.prototype.isValid = function () {
  52091. return true;
  52092. };
  52093. /**
  52094. * Internal only
  52095. * @ignore
  52096. */
  52097. Condition.prototype._getProperty = function (propertyPath) {
  52098. return this._actionManager._getProperty(propertyPath);
  52099. };
  52100. /**
  52101. * Internal only
  52102. * @ignore
  52103. */
  52104. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52105. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52106. };
  52107. /**
  52108. * Serialize placeholder for child classes
  52109. * @returns the serialized object
  52110. */
  52111. Condition.prototype.serialize = function () {
  52112. };
  52113. /**
  52114. * Internal only
  52115. * @ignore
  52116. */
  52117. Condition.prototype._serialize = function (serializedCondition) {
  52118. return {
  52119. type: 2,
  52120. children: [],
  52121. name: serializedCondition.name,
  52122. properties: serializedCondition.properties
  52123. };
  52124. };
  52125. return Condition;
  52126. }());
  52127. BABYLON.Condition = Condition;
  52128. /**
  52129. * Defines specific conditional operators as extensions of Condition
  52130. */
  52131. var ValueCondition = /** @class */ (function (_super) {
  52132. __extends(ValueCondition, _super);
  52133. /**
  52134. * Creates a new ValueCondition
  52135. * @param actionManager manager for the action the condition applies to
  52136. * @param target for the action
  52137. * @param propertyPath path to specify the property of the target the conditional operator uses
  52138. * @param value the value compared by the conditional operator against the current value of the property
  52139. * @param operator the conditional operator, default ValueCondition.IsEqual
  52140. */
  52141. function ValueCondition(actionManager, target,
  52142. /** path to specify the property of the target the conditional operator uses */
  52143. propertyPath,
  52144. /** the value compared by the conditional operator against the current value of the property */
  52145. value,
  52146. /** the conditional operator, default ValueCondition.IsEqual */
  52147. operator) {
  52148. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52149. var _this = _super.call(this, actionManager) || this;
  52150. _this.propertyPath = propertyPath;
  52151. _this.value = value;
  52152. _this.operator = operator;
  52153. _this._target = target;
  52154. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52155. _this._property = _this._getProperty(_this.propertyPath);
  52156. return _this;
  52157. }
  52158. Object.defineProperty(ValueCondition, "IsEqual", {
  52159. /**
  52160. * returns the number for IsEqual
  52161. */
  52162. get: function () {
  52163. return ValueCondition._IsEqual;
  52164. },
  52165. enumerable: true,
  52166. configurable: true
  52167. });
  52168. Object.defineProperty(ValueCondition, "IsDifferent", {
  52169. /**
  52170. * Returns the number for IsDifferent
  52171. */
  52172. get: function () {
  52173. return ValueCondition._IsDifferent;
  52174. },
  52175. enumerable: true,
  52176. configurable: true
  52177. });
  52178. Object.defineProperty(ValueCondition, "IsGreater", {
  52179. /**
  52180. * Returns the number for IsGreater
  52181. */
  52182. get: function () {
  52183. return ValueCondition._IsGreater;
  52184. },
  52185. enumerable: true,
  52186. configurable: true
  52187. });
  52188. Object.defineProperty(ValueCondition, "IsLesser", {
  52189. /**
  52190. * Returns the number for IsLesser
  52191. */
  52192. get: function () {
  52193. return ValueCondition._IsLesser;
  52194. },
  52195. enumerable: true,
  52196. configurable: true
  52197. });
  52198. /**
  52199. * Compares the given value with the property value for the specified conditional operator
  52200. * @returns the result of the comparison
  52201. */
  52202. ValueCondition.prototype.isValid = function () {
  52203. switch (this.operator) {
  52204. case ValueCondition.IsGreater:
  52205. return this._effectiveTarget[this._property] > this.value;
  52206. case ValueCondition.IsLesser:
  52207. return this._effectiveTarget[this._property] < this.value;
  52208. case ValueCondition.IsEqual:
  52209. case ValueCondition.IsDifferent:
  52210. var check;
  52211. if (this.value.equals) {
  52212. check = this.value.equals(this._effectiveTarget[this._property]);
  52213. }
  52214. else {
  52215. check = this.value === this._effectiveTarget[this._property];
  52216. }
  52217. return this.operator === ValueCondition.IsEqual ? check : !check;
  52218. }
  52219. return false;
  52220. };
  52221. /**
  52222. * Serialize the ValueCondition into a JSON compatible object
  52223. * @returns serialization object
  52224. */
  52225. ValueCondition.prototype.serialize = function () {
  52226. return this._serialize({
  52227. name: "ValueCondition",
  52228. properties: [
  52229. BABYLON.Action._GetTargetProperty(this._target),
  52230. { name: "propertyPath", value: this.propertyPath },
  52231. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52232. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52233. ]
  52234. });
  52235. };
  52236. /**
  52237. * Gets the name of the conditional operator for the ValueCondition
  52238. * @param operator the conditional operator
  52239. * @returns the name
  52240. */
  52241. ValueCondition.GetOperatorName = function (operator) {
  52242. switch (operator) {
  52243. case ValueCondition._IsEqual: return "IsEqual";
  52244. case ValueCondition._IsDifferent: return "IsDifferent";
  52245. case ValueCondition._IsGreater: return "IsGreater";
  52246. case ValueCondition._IsLesser: return "IsLesser";
  52247. default: return "";
  52248. }
  52249. };
  52250. /**
  52251. * Internal only
  52252. * @ignore
  52253. */
  52254. ValueCondition._IsEqual = 0;
  52255. /**
  52256. * Internal only
  52257. * @ignore
  52258. */
  52259. ValueCondition._IsDifferent = 1;
  52260. /**
  52261. * Internal only
  52262. * @ignore
  52263. */
  52264. ValueCondition._IsGreater = 2;
  52265. /**
  52266. * Internal only
  52267. * @ignore
  52268. */
  52269. ValueCondition._IsLesser = 3;
  52270. return ValueCondition;
  52271. }(Condition));
  52272. BABYLON.ValueCondition = ValueCondition;
  52273. /**
  52274. * Defines a predicate condition as an extension of Condition
  52275. */
  52276. var PredicateCondition = /** @class */ (function (_super) {
  52277. __extends(PredicateCondition, _super);
  52278. /**
  52279. * Creates a new PredicateCondition
  52280. * @param actionManager manager for the action the condition applies to
  52281. * @param predicate defines the predicate function used to validate the condition
  52282. */
  52283. function PredicateCondition(actionManager,
  52284. /** defines the predicate function used to validate the condition */
  52285. predicate) {
  52286. var _this = _super.call(this, actionManager) || this;
  52287. _this.predicate = predicate;
  52288. return _this;
  52289. }
  52290. /**
  52291. * @returns the validity of the predicate condition
  52292. */
  52293. PredicateCondition.prototype.isValid = function () {
  52294. return this.predicate();
  52295. };
  52296. return PredicateCondition;
  52297. }(Condition));
  52298. BABYLON.PredicateCondition = PredicateCondition;
  52299. /**
  52300. * Defines a state condition as an extension of Condition
  52301. */
  52302. var StateCondition = /** @class */ (function (_super) {
  52303. __extends(StateCondition, _super);
  52304. /**
  52305. * Creates a new StateCondition
  52306. * @param actionManager manager for the action the condition applies to
  52307. * @param target of the condition
  52308. * @param value to compare with target state
  52309. */
  52310. function StateCondition(actionManager, target, value) {
  52311. var _this = _super.call(this, actionManager) || this;
  52312. _this.value = value;
  52313. _this._target = target;
  52314. return _this;
  52315. }
  52316. /**
  52317. * @returns the validity of the state
  52318. */
  52319. StateCondition.prototype.isValid = function () {
  52320. return this._target.state === this.value;
  52321. };
  52322. /**
  52323. * Serialize the StateCondition into a JSON compatible object
  52324. * @returns serialization object
  52325. */
  52326. StateCondition.prototype.serialize = function () {
  52327. return this._serialize({
  52328. name: "StateCondition",
  52329. properties: [
  52330. BABYLON.Action._GetTargetProperty(this._target),
  52331. { name: "value", value: this.value }
  52332. ]
  52333. });
  52334. };
  52335. return StateCondition;
  52336. }(Condition));
  52337. BABYLON.StateCondition = StateCondition;
  52338. })(BABYLON || (BABYLON = {}));
  52339. //# sourceMappingURL=babylon.condition.js.map
  52340. var BABYLON;
  52341. (function (BABYLON) {
  52342. /**
  52343. * The action to be carried out following a trigger
  52344. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52345. */
  52346. var Action = /** @class */ (function () {
  52347. /**
  52348. * Creates a new Action
  52349. * @param triggerOptions the trigger, with or without parameters, for the action
  52350. * @param condition an optional determinant of action
  52351. */
  52352. function Action(triggerOptions, condition) {
  52353. this.triggerOptions = triggerOptions;
  52354. /**
  52355. * An event triggered prior to action being executed.
  52356. */
  52357. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52358. if (triggerOptions.parameter) {
  52359. this.trigger = triggerOptions.trigger;
  52360. this._triggerParameter = triggerOptions.parameter;
  52361. }
  52362. else {
  52363. this.trigger = triggerOptions;
  52364. }
  52365. this._nextActiveAction = this;
  52366. this._condition = condition;
  52367. }
  52368. /**
  52369. * Internal only
  52370. * @ignore
  52371. */
  52372. Action.prototype._prepare = function () {
  52373. };
  52374. /**
  52375. * Gets the trigger parameters
  52376. * @returns the trigger parameters
  52377. */
  52378. Action.prototype.getTriggerParameter = function () {
  52379. return this._triggerParameter;
  52380. };
  52381. /**
  52382. * Internal only - executes current action event
  52383. * @ignore
  52384. */
  52385. Action.prototype._executeCurrent = function (evt) {
  52386. if (this._nextActiveAction._condition) {
  52387. var condition = this._nextActiveAction._condition;
  52388. var currentRenderId = this._actionManager.getScene().getRenderId();
  52389. // We cache the current evaluation for the current frame
  52390. if (condition._evaluationId === currentRenderId) {
  52391. if (!condition._currentResult) {
  52392. return;
  52393. }
  52394. }
  52395. else {
  52396. condition._evaluationId = currentRenderId;
  52397. if (!condition.isValid()) {
  52398. condition._currentResult = false;
  52399. return;
  52400. }
  52401. condition._currentResult = true;
  52402. }
  52403. }
  52404. this.onBeforeExecuteObservable.notifyObservers(this);
  52405. this._nextActiveAction.execute(evt);
  52406. this.skipToNextActiveAction();
  52407. };
  52408. /**
  52409. * Execute placeholder for child classes
  52410. * @param evt optional action event
  52411. */
  52412. Action.prototype.execute = function (evt) {
  52413. };
  52414. /**
  52415. * Skips to next active action
  52416. */
  52417. Action.prototype.skipToNextActiveAction = function () {
  52418. if (this._nextActiveAction._child) {
  52419. if (!this._nextActiveAction._child._actionManager) {
  52420. this._nextActiveAction._child._actionManager = this._actionManager;
  52421. }
  52422. this._nextActiveAction = this._nextActiveAction._child;
  52423. }
  52424. else {
  52425. this._nextActiveAction = this;
  52426. }
  52427. };
  52428. /**
  52429. * Adds action to chain of actions, may be a DoNothingAction
  52430. * @param index The index of the attribute.
  52431. * @returns The action passed in
  52432. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52433. */
  52434. Action.prototype.then = function (action) {
  52435. this._child = action;
  52436. action._actionManager = this._actionManager;
  52437. action._prepare();
  52438. return action;
  52439. };
  52440. /**
  52441. * Internal only
  52442. * @ignore
  52443. */
  52444. Action.prototype._getProperty = function (propertyPath) {
  52445. return this._actionManager._getProperty(propertyPath);
  52446. };
  52447. /**
  52448. * Internal only
  52449. * @ignore
  52450. */
  52451. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52452. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52453. };
  52454. /**
  52455. * Serialize placeholder for child classes
  52456. * @param parent of child
  52457. * @returns the serialized object
  52458. */
  52459. Action.prototype.serialize = function (parent) {
  52460. };
  52461. /**
  52462. * Internal only called by serialize
  52463. * @ignore
  52464. */
  52465. Action.prototype._serialize = function (serializedAction, parent) {
  52466. var serializationObject = {
  52467. type: 1,
  52468. children: [],
  52469. name: serializedAction.name,
  52470. properties: serializedAction.properties || []
  52471. };
  52472. // Serialize child
  52473. if (this._child) {
  52474. this._child.serialize(serializationObject);
  52475. }
  52476. // Check if "this" has a condition
  52477. if (this._condition) {
  52478. var serializedCondition = this._condition.serialize();
  52479. serializedCondition.children.push(serializationObject);
  52480. if (parent) {
  52481. parent.children.push(serializedCondition);
  52482. }
  52483. return serializedCondition;
  52484. }
  52485. if (parent) {
  52486. parent.children.push(serializationObject);
  52487. }
  52488. return serializationObject;
  52489. };
  52490. /**
  52491. * Internal only
  52492. * @ignore
  52493. */
  52494. Action._SerializeValueAsString = function (value) {
  52495. if (typeof value === "number") {
  52496. return value.toString();
  52497. }
  52498. if (typeof value === "boolean") {
  52499. return value ? "true" : "false";
  52500. }
  52501. if (value instanceof BABYLON.Vector2) {
  52502. return value.x + ", " + value.y;
  52503. }
  52504. if (value instanceof BABYLON.Vector3) {
  52505. return value.x + ", " + value.y + ", " + value.z;
  52506. }
  52507. if (value instanceof BABYLON.Color3) {
  52508. return value.r + ", " + value.g + ", " + value.b;
  52509. }
  52510. if (value instanceof BABYLON.Color4) {
  52511. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52512. }
  52513. return value; // string
  52514. };
  52515. /**
  52516. * Internal only
  52517. * @ignore
  52518. */
  52519. Action._GetTargetProperty = function (target) {
  52520. return {
  52521. name: "target",
  52522. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52523. : target instanceof BABYLON.Light ? "LightProperties"
  52524. : target instanceof BABYLON.Camera ? "CameraProperties"
  52525. : "SceneProperties",
  52526. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52527. };
  52528. };
  52529. return Action;
  52530. }());
  52531. BABYLON.Action = Action;
  52532. })(BABYLON || (BABYLON = {}));
  52533. //# sourceMappingURL=babylon.action.js.map
  52534. var BABYLON;
  52535. (function (BABYLON) {
  52536. /**
  52537. * ActionEvent is the event being sent when an action is triggered.
  52538. */
  52539. var ActionEvent = /** @class */ (function () {
  52540. /**
  52541. * @param source The mesh or sprite that triggered the action.
  52542. * @param pointerX The X mouse cursor position at the time of the event
  52543. * @param pointerY The Y mouse cursor position at the time of the event
  52544. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52545. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52546. */
  52547. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52548. this.source = source;
  52549. this.pointerX = pointerX;
  52550. this.pointerY = pointerY;
  52551. this.meshUnderPointer = meshUnderPointer;
  52552. this.sourceEvent = sourceEvent;
  52553. this.additionalData = additionalData;
  52554. }
  52555. /**
  52556. * Helper function to auto-create an ActionEvent from a source mesh.
  52557. * @param source The source mesh that triggered the event
  52558. * @param evt {Event} The original (browser) event
  52559. */
  52560. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52561. var scene = source.getScene();
  52562. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52563. };
  52564. /**
  52565. * Helper function to auto-create an ActionEvent from a source mesh.
  52566. * @param source The source sprite that triggered the event
  52567. * @param scene Scene associated with the sprite
  52568. * @param evt {Event} The original (browser) event
  52569. */
  52570. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52571. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52572. };
  52573. /**
  52574. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52575. * @param scene the scene where the event occurred
  52576. * @param evt {Event} The original (browser) event
  52577. */
  52578. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52579. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52580. };
  52581. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52582. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52583. };
  52584. return ActionEvent;
  52585. }());
  52586. BABYLON.ActionEvent = ActionEvent;
  52587. /**
  52588. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52589. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52590. */
  52591. var ActionManager = /** @class */ (function () {
  52592. function ActionManager(scene) {
  52593. // Members
  52594. this.actions = new Array();
  52595. this.hoverCursor = '';
  52596. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52597. scene._actionManagers.push(this);
  52598. }
  52599. Object.defineProperty(ActionManager, "NothingTrigger", {
  52600. get: function () {
  52601. return ActionManager._NothingTrigger;
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52607. get: function () {
  52608. return ActionManager._OnPickTrigger;
  52609. },
  52610. enumerable: true,
  52611. configurable: true
  52612. });
  52613. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52614. get: function () {
  52615. return ActionManager._OnLeftPickTrigger;
  52616. },
  52617. enumerable: true,
  52618. configurable: true
  52619. });
  52620. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52621. get: function () {
  52622. return ActionManager._OnRightPickTrigger;
  52623. },
  52624. enumerable: true,
  52625. configurable: true
  52626. });
  52627. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52628. get: function () {
  52629. return ActionManager._OnCenterPickTrigger;
  52630. },
  52631. enumerable: true,
  52632. configurable: true
  52633. });
  52634. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52635. get: function () {
  52636. return ActionManager._OnPickDownTrigger;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52642. get: function () {
  52643. return ActionManager._OnDoublePickTrigger;
  52644. },
  52645. enumerable: true,
  52646. configurable: true
  52647. });
  52648. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52649. get: function () {
  52650. return ActionManager._OnPickUpTrigger;
  52651. },
  52652. enumerable: true,
  52653. configurable: true
  52654. });
  52655. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52656. /// This trigger will only be raised if you also declared a OnPickDown
  52657. get: function () {
  52658. return ActionManager._OnPickOutTrigger;
  52659. },
  52660. enumerable: true,
  52661. configurable: true
  52662. });
  52663. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52664. get: function () {
  52665. return ActionManager._OnLongPressTrigger;
  52666. },
  52667. enumerable: true,
  52668. configurable: true
  52669. });
  52670. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52671. get: function () {
  52672. return ActionManager._OnPointerOverTrigger;
  52673. },
  52674. enumerable: true,
  52675. configurable: true
  52676. });
  52677. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52678. get: function () {
  52679. return ActionManager._OnPointerOutTrigger;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52685. get: function () {
  52686. return ActionManager._OnEveryFrameTrigger;
  52687. },
  52688. enumerable: true,
  52689. configurable: true
  52690. });
  52691. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52692. get: function () {
  52693. return ActionManager._OnIntersectionEnterTrigger;
  52694. },
  52695. enumerable: true,
  52696. configurable: true
  52697. });
  52698. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52699. get: function () {
  52700. return ActionManager._OnIntersectionExitTrigger;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52706. get: function () {
  52707. return ActionManager._OnKeyDownTrigger;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52713. get: function () {
  52714. return ActionManager._OnKeyUpTrigger;
  52715. },
  52716. enumerable: true,
  52717. configurable: true
  52718. });
  52719. // Methods
  52720. ActionManager.prototype.dispose = function () {
  52721. var index = this._scene._actionManagers.indexOf(this);
  52722. for (var i = 0; i < this.actions.length; i++) {
  52723. var action = this.actions[i];
  52724. ActionManager.Triggers[action.trigger]--;
  52725. if (ActionManager.Triggers[action.trigger] === 0) {
  52726. delete ActionManager.Triggers[action.trigger];
  52727. }
  52728. }
  52729. if (index > -1) {
  52730. this._scene._actionManagers.splice(index, 1);
  52731. }
  52732. };
  52733. ActionManager.prototype.getScene = function () {
  52734. return this._scene;
  52735. };
  52736. /**
  52737. * Does this action manager handles actions of any of the given triggers
  52738. * @param {number[]} triggers - the triggers to be tested
  52739. * @return {boolean} whether one (or more) of the triggers is handeled
  52740. */
  52741. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52742. for (var index = 0; index < this.actions.length; index++) {
  52743. var action = this.actions[index];
  52744. if (triggers.indexOf(action.trigger) > -1) {
  52745. return true;
  52746. }
  52747. }
  52748. return false;
  52749. };
  52750. /**
  52751. * Does this action manager handles actions of a given trigger
  52752. * @param trigger defines the trigger to be tested
  52753. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52754. * @return whether the trigger is handled
  52755. */
  52756. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52757. for (var index = 0; index < this.actions.length; index++) {
  52758. var action = this.actions[index];
  52759. if (action.trigger === trigger) {
  52760. if (parameterPredicate) {
  52761. if (parameterPredicate(action.getTriggerParameter())) {
  52762. return true;
  52763. }
  52764. }
  52765. else {
  52766. return true;
  52767. }
  52768. }
  52769. }
  52770. return false;
  52771. };
  52772. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52773. /**
  52774. * Does this action manager has pointer triggers
  52775. * @return {boolean} whether or not it has pointer triggers
  52776. */
  52777. get: function () {
  52778. for (var index = 0; index < this.actions.length; index++) {
  52779. var action = this.actions[index];
  52780. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52781. return true;
  52782. }
  52783. }
  52784. return false;
  52785. },
  52786. enumerable: true,
  52787. configurable: true
  52788. });
  52789. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52790. /**
  52791. * Does this action manager has pick triggers
  52792. * @return {boolean} whether or not it has pick triggers
  52793. */
  52794. get: function () {
  52795. for (var index = 0; index < this.actions.length; index++) {
  52796. var action = this.actions[index];
  52797. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52798. return true;
  52799. }
  52800. }
  52801. return false;
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(ActionManager, "HasTriggers", {
  52807. /**
  52808. * Does exist one action manager with at least one trigger
  52809. * @return {boolean} whether or not it exists one action manager with one trigger
  52810. **/
  52811. get: function () {
  52812. for (var t in ActionManager.Triggers) {
  52813. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52814. return true;
  52815. }
  52816. }
  52817. return false;
  52818. },
  52819. enumerable: true,
  52820. configurable: true
  52821. });
  52822. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52823. /**
  52824. * Does exist one action manager with at least one pick trigger
  52825. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52826. **/
  52827. get: function () {
  52828. for (var t in ActionManager.Triggers) {
  52829. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52830. var t_int = parseInt(t);
  52831. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52832. return true;
  52833. }
  52834. }
  52835. }
  52836. return false;
  52837. },
  52838. enumerable: true,
  52839. configurable: true
  52840. });
  52841. /**
  52842. * Does exist one action manager that handles actions of a given trigger
  52843. * @param {number} trigger - the trigger to be tested
  52844. * @return {boolean} whether the trigger is handeled by at least one action manager
  52845. **/
  52846. ActionManager.HasSpecificTrigger = function (trigger) {
  52847. for (var t in ActionManager.Triggers) {
  52848. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52849. var t_int = parseInt(t);
  52850. if (t_int === trigger) {
  52851. return true;
  52852. }
  52853. }
  52854. }
  52855. return false;
  52856. };
  52857. /**
  52858. * Registers an action to this action manager
  52859. * @param {BABYLON.Action} action - the action to be registered
  52860. * @return {BABYLON.Action} the action amended (prepared) after registration
  52861. */
  52862. ActionManager.prototype.registerAction = function (action) {
  52863. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52864. if (this.getScene().actionManager !== this) {
  52865. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52866. return null;
  52867. }
  52868. }
  52869. this.actions.push(action);
  52870. if (ActionManager.Triggers[action.trigger]) {
  52871. ActionManager.Triggers[action.trigger]++;
  52872. }
  52873. else {
  52874. ActionManager.Triggers[action.trigger] = 1;
  52875. }
  52876. action._actionManager = this;
  52877. action._prepare();
  52878. return action;
  52879. };
  52880. /**
  52881. * Unregisters an action to this action manager
  52882. * @param action The action to be unregistered
  52883. * @return whether the action has been unregistered
  52884. */
  52885. ActionManager.prototype.unregisterAction = function (action) {
  52886. var index = this.actions.indexOf(action);
  52887. if (index !== -1) {
  52888. this.actions.splice(index, 1);
  52889. ActionManager.Triggers[action.trigger] -= 1;
  52890. if (ActionManager.Triggers[action.trigger] === 0) {
  52891. delete ActionManager.Triggers[action.trigger];
  52892. }
  52893. delete action._actionManager;
  52894. return true;
  52895. }
  52896. return false;
  52897. };
  52898. /**
  52899. * Process a specific trigger
  52900. * @param {number} trigger - the trigger to process
  52901. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52902. */
  52903. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52904. for (var index = 0; index < this.actions.length; index++) {
  52905. var action = this.actions[index];
  52906. if (action.trigger === trigger) {
  52907. if (evt) {
  52908. if (trigger === ActionManager.OnKeyUpTrigger
  52909. || trigger === ActionManager.OnKeyDownTrigger) {
  52910. var parameter = action.getTriggerParameter();
  52911. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52912. if (!parameter.toLowerCase) {
  52913. continue;
  52914. }
  52915. var lowerCase = parameter.toLowerCase();
  52916. if (lowerCase !== evt.sourceEvent.key) {
  52917. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52918. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52919. if (actualkey !== lowerCase) {
  52920. continue;
  52921. }
  52922. }
  52923. }
  52924. }
  52925. }
  52926. action._executeCurrent(evt);
  52927. }
  52928. }
  52929. };
  52930. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52931. var properties = propertyPath.split(".");
  52932. for (var index = 0; index < properties.length - 1; index++) {
  52933. target = target[properties[index]];
  52934. }
  52935. return target;
  52936. };
  52937. ActionManager.prototype._getProperty = function (propertyPath) {
  52938. var properties = propertyPath.split(".");
  52939. return properties[properties.length - 1];
  52940. };
  52941. ActionManager.prototype.serialize = function (name) {
  52942. var root = {
  52943. children: new Array(),
  52944. name: name,
  52945. type: 3,
  52946. properties: new Array() // Empty for root but required
  52947. };
  52948. for (var i = 0; i < this.actions.length; i++) {
  52949. var triggerObject = {
  52950. type: 0,
  52951. children: new Array(),
  52952. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52953. properties: new Array()
  52954. };
  52955. var triggerOptions = this.actions[i].triggerOptions;
  52956. if (triggerOptions && typeof triggerOptions !== "number") {
  52957. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52958. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52959. }
  52960. else {
  52961. var parameter = {};
  52962. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52963. if (triggerOptions.parameter.mesh) {
  52964. parameter._meshId = triggerOptions.parameter.mesh.id;
  52965. }
  52966. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52967. }
  52968. }
  52969. // Serialize child action, recursively
  52970. this.actions[i].serialize(triggerObject);
  52971. // Add serialized trigger
  52972. root.children.push(triggerObject);
  52973. }
  52974. return root;
  52975. };
  52976. ActionManager.Parse = function (parsedActions, object, scene) {
  52977. var actionManager = new ActionManager(scene);
  52978. if (object === null)
  52979. scene.actionManager = actionManager;
  52980. else
  52981. object.actionManager = actionManager;
  52982. // instanciate a new object
  52983. var instanciate = function (name, params) {
  52984. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52985. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52986. newInstance.constructor.apply(newInstance, params);
  52987. return newInstance;
  52988. };
  52989. var parseParameter = function (name, value, target, propertyPath) {
  52990. if (propertyPath === null) {
  52991. // String, boolean or float
  52992. var floatValue = parseFloat(value);
  52993. if (value === "true" || value === "false")
  52994. return value === "true";
  52995. else
  52996. return isNaN(floatValue) ? value : floatValue;
  52997. }
  52998. var effectiveTarget = propertyPath.split(".");
  52999. var values = value.split(",");
  53000. // Get effective Target
  53001. for (var i = 0; i < effectiveTarget.length; i++) {
  53002. target = target[effectiveTarget[i]];
  53003. }
  53004. // Return appropriate value with its type
  53005. if (typeof (target) === "boolean")
  53006. return values[0] === "true";
  53007. if (typeof (target) === "string")
  53008. return values[0];
  53009. // Parameters with multiple values such as Vector3 etc.
  53010. var split = new Array();
  53011. for (var i = 0; i < values.length; i++)
  53012. split.push(parseFloat(values[i]));
  53013. if (target instanceof BABYLON.Vector3)
  53014. return BABYLON.Vector3.FromArray(split);
  53015. if (target instanceof BABYLON.Vector4)
  53016. return BABYLON.Vector4.FromArray(split);
  53017. if (target instanceof BABYLON.Color3)
  53018. return BABYLON.Color3.FromArray(split);
  53019. if (target instanceof BABYLON.Color4)
  53020. return BABYLON.Color4.FromArray(split);
  53021. return parseFloat(values[0]);
  53022. };
  53023. // traverse graph per trigger
  53024. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53025. if (combineArray === void 0) { combineArray = null; }
  53026. if (parsedAction.detached)
  53027. return;
  53028. var parameters = new Array();
  53029. var target = null;
  53030. var propertyPath = null;
  53031. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53032. // Parameters
  53033. if (parsedAction.type === 2)
  53034. parameters.push(actionManager);
  53035. else
  53036. parameters.push(trigger);
  53037. if (combine) {
  53038. var actions = new Array();
  53039. for (var j = 0; j < parsedAction.combine.length; j++) {
  53040. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53041. }
  53042. parameters.push(actions);
  53043. }
  53044. else {
  53045. for (var i = 0; i < parsedAction.properties.length; i++) {
  53046. var value = parsedAction.properties[i].value;
  53047. var name = parsedAction.properties[i].name;
  53048. var targetType = parsedAction.properties[i].targetType;
  53049. if (name === "target")
  53050. if (targetType !== null && targetType === "SceneProperties")
  53051. value = target = scene;
  53052. else
  53053. value = target = scene.getNodeByName(value);
  53054. else if (name === "parent")
  53055. value = scene.getNodeByName(value);
  53056. else if (name === "sound")
  53057. value = scene.getSoundByName(value);
  53058. else if (name !== "propertyPath") {
  53059. if (parsedAction.type === 2 && name === "operator")
  53060. value = BABYLON.ValueCondition[value];
  53061. else
  53062. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53063. }
  53064. else {
  53065. propertyPath = value;
  53066. }
  53067. parameters.push(value);
  53068. }
  53069. }
  53070. if (combineArray === null) {
  53071. parameters.push(condition);
  53072. }
  53073. else {
  53074. parameters.push(null);
  53075. }
  53076. // If interpolate value action
  53077. if (parsedAction.name === "InterpolateValueAction") {
  53078. var param = parameters[parameters.length - 2];
  53079. parameters[parameters.length - 1] = param;
  53080. parameters[parameters.length - 2] = condition;
  53081. }
  53082. // Action or condition(s) and not CombineAction
  53083. var newAction = instanciate(parsedAction.name, parameters);
  53084. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53085. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53086. if (action)
  53087. action.then(nothing);
  53088. else
  53089. actionManager.registerAction(nothing);
  53090. action = nothing;
  53091. }
  53092. if (combineArray === null) {
  53093. if (newAction instanceof BABYLON.Condition) {
  53094. condition = newAction;
  53095. newAction = action;
  53096. }
  53097. else {
  53098. condition = null;
  53099. if (action)
  53100. action.then(newAction);
  53101. else
  53102. actionManager.registerAction(newAction);
  53103. }
  53104. }
  53105. else {
  53106. combineArray.push(newAction);
  53107. }
  53108. for (var i = 0; i < parsedAction.children.length; i++)
  53109. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53110. };
  53111. // triggers
  53112. for (var i = 0; i < parsedActions.children.length; i++) {
  53113. var triggerParams;
  53114. var trigger = parsedActions.children[i];
  53115. if (trigger.properties.length > 0) {
  53116. var param = trigger.properties[0].value;
  53117. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53118. if (value._meshId) {
  53119. value.mesh = scene.getMeshByID(value._meshId);
  53120. }
  53121. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53122. }
  53123. else
  53124. triggerParams = ActionManager[trigger.name];
  53125. for (var j = 0; j < trigger.children.length; j++) {
  53126. if (!trigger.detached)
  53127. traverse(trigger.children[j], triggerParams, null, null);
  53128. }
  53129. }
  53130. };
  53131. ActionManager.GetTriggerName = function (trigger) {
  53132. switch (trigger) {
  53133. case 0: return "NothingTrigger";
  53134. case 1: return "OnPickTrigger";
  53135. case 2: return "OnLeftPickTrigger";
  53136. case 3: return "OnRightPickTrigger";
  53137. case 4: return "OnCenterPickTrigger";
  53138. case 5: return "OnPickDownTrigger";
  53139. case 6: return "OnPickUpTrigger";
  53140. case 7: return "OnLongPressTrigger";
  53141. case 8: return "OnPointerOverTrigger";
  53142. case 9: return "OnPointerOutTrigger";
  53143. case 10: return "OnEveryFrameTrigger";
  53144. case 11: return "OnIntersectionEnterTrigger";
  53145. case 12: return "OnIntersectionExitTrigger";
  53146. case 13: return "OnKeyDownTrigger";
  53147. case 14: return "OnKeyUpTrigger";
  53148. case 15: return "OnPickOutTrigger";
  53149. default: return "";
  53150. }
  53151. };
  53152. // Statics
  53153. ActionManager._NothingTrigger = 0;
  53154. ActionManager._OnPickTrigger = 1;
  53155. ActionManager._OnLeftPickTrigger = 2;
  53156. ActionManager._OnRightPickTrigger = 3;
  53157. ActionManager._OnCenterPickTrigger = 4;
  53158. ActionManager._OnPickDownTrigger = 5;
  53159. ActionManager._OnDoublePickTrigger = 6;
  53160. ActionManager._OnPickUpTrigger = 7;
  53161. ActionManager._OnLongPressTrigger = 8;
  53162. ActionManager._OnPointerOverTrigger = 9;
  53163. ActionManager._OnPointerOutTrigger = 10;
  53164. ActionManager._OnEveryFrameTrigger = 11;
  53165. ActionManager._OnIntersectionEnterTrigger = 12;
  53166. ActionManager._OnIntersectionExitTrigger = 13;
  53167. ActionManager._OnKeyDownTrigger = 14;
  53168. ActionManager._OnKeyUpTrigger = 15;
  53169. ActionManager._OnPickOutTrigger = 16;
  53170. ActionManager.Triggers = {};
  53171. return ActionManager;
  53172. }());
  53173. BABYLON.ActionManager = ActionManager;
  53174. })(BABYLON || (BABYLON = {}));
  53175. //# sourceMappingURL=babylon.actionManager.js.map
  53176. var BABYLON;
  53177. (function (BABYLON) {
  53178. var InterpolateValueAction = /** @class */ (function (_super) {
  53179. __extends(InterpolateValueAction, _super);
  53180. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53181. if (duration === void 0) { duration = 1000; }
  53182. var _this = _super.call(this, triggerOptions, condition) || this;
  53183. _this.propertyPath = propertyPath;
  53184. _this.value = value;
  53185. _this.duration = duration;
  53186. _this.stopOtherAnimations = stopOtherAnimations;
  53187. _this.onInterpolationDone = onInterpolationDone;
  53188. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53189. _this._target = _this._effectiveTarget = target;
  53190. return _this;
  53191. }
  53192. InterpolateValueAction.prototype._prepare = function () {
  53193. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53194. this._property = this._getProperty(this.propertyPath);
  53195. };
  53196. InterpolateValueAction.prototype.execute = function () {
  53197. var _this = this;
  53198. var scene = this._actionManager.getScene();
  53199. var keys = [
  53200. {
  53201. frame: 0,
  53202. value: this._effectiveTarget[this._property]
  53203. }, {
  53204. frame: 100,
  53205. value: this.value
  53206. }
  53207. ];
  53208. var dataType;
  53209. if (typeof this.value === "number") {
  53210. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53211. }
  53212. else if (this.value instanceof BABYLON.Color3) {
  53213. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53214. }
  53215. else if (this.value instanceof BABYLON.Vector3) {
  53216. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53217. }
  53218. else if (this.value instanceof BABYLON.Matrix) {
  53219. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53220. }
  53221. else if (this.value instanceof BABYLON.Quaternion) {
  53222. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53223. }
  53224. else {
  53225. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53226. return;
  53227. }
  53228. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53229. animation.setKeys(keys);
  53230. if (this.stopOtherAnimations) {
  53231. scene.stopAnimation(this._effectiveTarget);
  53232. }
  53233. var wrapper = function () {
  53234. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53235. if (_this.onInterpolationDone) {
  53236. _this.onInterpolationDone();
  53237. }
  53238. };
  53239. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53240. };
  53241. InterpolateValueAction.prototype.serialize = function (parent) {
  53242. return _super.prototype._serialize.call(this, {
  53243. name: "InterpolateValueAction",
  53244. properties: [
  53245. BABYLON.Action._GetTargetProperty(this._target),
  53246. { name: "propertyPath", value: this.propertyPath },
  53247. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53248. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53249. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53250. ]
  53251. }, parent);
  53252. };
  53253. return InterpolateValueAction;
  53254. }(BABYLON.Action));
  53255. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53256. })(BABYLON || (BABYLON = {}));
  53257. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53258. var BABYLON;
  53259. (function (BABYLON) {
  53260. var SwitchBooleanAction = /** @class */ (function (_super) {
  53261. __extends(SwitchBooleanAction, _super);
  53262. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53263. var _this = _super.call(this, triggerOptions, condition) || this;
  53264. _this.propertyPath = propertyPath;
  53265. _this._target = _this._effectiveTarget = target;
  53266. return _this;
  53267. }
  53268. SwitchBooleanAction.prototype._prepare = function () {
  53269. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53270. this._property = this._getProperty(this.propertyPath);
  53271. };
  53272. SwitchBooleanAction.prototype.execute = function () {
  53273. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53274. };
  53275. SwitchBooleanAction.prototype.serialize = function (parent) {
  53276. return _super.prototype._serialize.call(this, {
  53277. name: "SwitchBooleanAction",
  53278. properties: [
  53279. BABYLON.Action._GetTargetProperty(this._target),
  53280. { name: "propertyPath", value: this.propertyPath }
  53281. ]
  53282. }, parent);
  53283. };
  53284. return SwitchBooleanAction;
  53285. }(BABYLON.Action));
  53286. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53287. var SetStateAction = /** @class */ (function (_super) {
  53288. __extends(SetStateAction, _super);
  53289. function SetStateAction(triggerOptions, target, value, condition) {
  53290. var _this = _super.call(this, triggerOptions, condition) || this;
  53291. _this.value = value;
  53292. _this._target = target;
  53293. return _this;
  53294. }
  53295. SetStateAction.prototype.execute = function () {
  53296. this._target.state = this.value;
  53297. };
  53298. SetStateAction.prototype.serialize = function (parent) {
  53299. return _super.prototype._serialize.call(this, {
  53300. name: "SetStateAction",
  53301. properties: [
  53302. BABYLON.Action._GetTargetProperty(this._target),
  53303. { name: "value", value: this.value }
  53304. ]
  53305. }, parent);
  53306. };
  53307. return SetStateAction;
  53308. }(BABYLON.Action));
  53309. BABYLON.SetStateAction = SetStateAction;
  53310. var SetValueAction = /** @class */ (function (_super) {
  53311. __extends(SetValueAction, _super);
  53312. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53313. var _this = _super.call(this, triggerOptions, condition) || this;
  53314. _this.propertyPath = propertyPath;
  53315. _this.value = value;
  53316. _this._target = _this._effectiveTarget = target;
  53317. return _this;
  53318. }
  53319. SetValueAction.prototype._prepare = function () {
  53320. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53321. this._property = this._getProperty(this.propertyPath);
  53322. };
  53323. SetValueAction.prototype.execute = function () {
  53324. this._effectiveTarget[this._property] = this.value;
  53325. if (this._target.markAsDirty) {
  53326. this._target.markAsDirty(this._property);
  53327. }
  53328. };
  53329. SetValueAction.prototype.serialize = function (parent) {
  53330. return _super.prototype._serialize.call(this, {
  53331. name: "SetValueAction",
  53332. properties: [
  53333. BABYLON.Action._GetTargetProperty(this._target),
  53334. { name: "propertyPath", value: this.propertyPath },
  53335. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53336. ]
  53337. }, parent);
  53338. };
  53339. return SetValueAction;
  53340. }(BABYLON.Action));
  53341. BABYLON.SetValueAction = SetValueAction;
  53342. var IncrementValueAction = /** @class */ (function (_super) {
  53343. __extends(IncrementValueAction, _super);
  53344. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53345. var _this = _super.call(this, triggerOptions, condition) || this;
  53346. _this.propertyPath = propertyPath;
  53347. _this.value = value;
  53348. _this._target = _this._effectiveTarget = target;
  53349. return _this;
  53350. }
  53351. IncrementValueAction.prototype._prepare = function () {
  53352. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53353. this._property = this._getProperty(this.propertyPath);
  53354. if (typeof this._effectiveTarget[this._property] !== "number") {
  53355. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53356. }
  53357. };
  53358. IncrementValueAction.prototype.execute = function () {
  53359. this._effectiveTarget[this._property] += this.value;
  53360. if (this._target.markAsDirty) {
  53361. this._target.markAsDirty(this._property);
  53362. }
  53363. };
  53364. IncrementValueAction.prototype.serialize = function (parent) {
  53365. return _super.prototype._serialize.call(this, {
  53366. name: "IncrementValueAction",
  53367. properties: [
  53368. BABYLON.Action._GetTargetProperty(this._target),
  53369. { name: "propertyPath", value: this.propertyPath },
  53370. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53371. ]
  53372. }, parent);
  53373. };
  53374. return IncrementValueAction;
  53375. }(BABYLON.Action));
  53376. BABYLON.IncrementValueAction = IncrementValueAction;
  53377. var PlayAnimationAction = /** @class */ (function (_super) {
  53378. __extends(PlayAnimationAction, _super);
  53379. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53380. var _this = _super.call(this, triggerOptions, condition) || this;
  53381. _this.from = from;
  53382. _this.to = to;
  53383. _this.loop = loop;
  53384. _this._target = target;
  53385. return _this;
  53386. }
  53387. PlayAnimationAction.prototype._prepare = function () {
  53388. };
  53389. PlayAnimationAction.prototype.execute = function () {
  53390. var scene = this._actionManager.getScene();
  53391. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53392. };
  53393. PlayAnimationAction.prototype.serialize = function (parent) {
  53394. return _super.prototype._serialize.call(this, {
  53395. name: "PlayAnimationAction",
  53396. properties: [
  53397. BABYLON.Action._GetTargetProperty(this._target),
  53398. { name: "from", value: String(this.from) },
  53399. { name: "to", value: String(this.to) },
  53400. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53401. ]
  53402. }, parent);
  53403. };
  53404. return PlayAnimationAction;
  53405. }(BABYLON.Action));
  53406. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53407. var StopAnimationAction = /** @class */ (function (_super) {
  53408. __extends(StopAnimationAction, _super);
  53409. function StopAnimationAction(triggerOptions, target, condition) {
  53410. var _this = _super.call(this, triggerOptions, condition) || this;
  53411. _this._target = target;
  53412. return _this;
  53413. }
  53414. StopAnimationAction.prototype._prepare = function () {
  53415. };
  53416. StopAnimationAction.prototype.execute = function () {
  53417. var scene = this._actionManager.getScene();
  53418. scene.stopAnimation(this._target);
  53419. };
  53420. StopAnimationAction.prototype.serialize = function (parent) {
  53421. return _super.prototype._serialize.call(this, {
  53422. name: "StopAnimationAction",
  53423. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53424. }, parent);
  53425. };
  53426. return StopAnimationAction;
  53427. }(BABYLON.Action));
  53428. BABYLON.StopAnimationAction = StopAnimationAction;
  53429. var DoNothingAction = /** @class */ (function (_super) {
  53430. __extends(DoNothingAction, _super);
  53431. function DoNothingAction(triggerOptions, condition) {
  53432. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53433. return _super.call(this, triggerOptions, condition) || this;
  53434. }
  53435. DoNothingAction.prototype.execute = function () {
  53436. };
  53437. DoNothingAction.prototype.serialize = function (parent) {
  53438. return _super.prototype._serialize.call(this, {
  53439. name: "DoNothingAction",
  53440. properties: []
  53441. }, parent);
  53442. };
  53443. return DoNothingAction;
  53444. }(BABYLON.Action));
  53445. BABYLON.DoNothingAction = DoNothingAction;
  53446. var CombineAction = /** @class */ (function (_super) {
  53447. __extends(CombineAction, _super);
  53448. function CombineAction(triggerOptions, children, condition) {
  53449. var _this = _super.call(this, triggerOptions, condition) || this;
  53450. _this.children = children;
  53451. return _this;
  53452. }
  53453. CombineAction.prototype._prepare = function () {
  53454. for (var index = 0; index < this.children.length; index++) {
  53455. this.children[index]._actionManager = this._actionManager;
  53456. this.children[index]._prepare();
  53457. }
  53458. };
  53459. CombineAction.prototype.execute = function (evt) {
  53460. for (var index = 0; index < this.children.length; index++) {
  53461. this.children[index].execute(evt);
  53462. }
  53463. };
  53464. CombineAction.prototype.serialize = function (parent) {
  53465. var serializationObject = _super.prototype._serialize.call(this, {
  53466. name: "CombineAction",
  53467. properties: [],
  53468. combine: []
  53469. }, parent);
  53470. for (var i = 0; i < this.children.length; i++) {
  53471. serializationObject.combine.push(this.children[i].serialize(null));
  53472. }
  53473. return serializationObject;
  53474. };
  53475. return CombineAction;
  53476. }(BABYLON.Action));
  53477. BABYLON.CombineAction = CombineAction;
  53478. var ExecuteCodeAction = /** @class */ (function (_super) {
  53479. __extends(ExecuteCodeAction, _super);
  53480. function ExecuteCodeAction(triggerOptions, func, condition) {
  53481. var _this = _super.call(this, triggerOptions, condition) || this;
  53482. _this.func = func;
  53483. return _this;
  53484. }
  53485. ExecuteCodeAction.prototype.execute = function (evt) {
  53486. this.func(evt);
  53487. };
  53488. return ExecuteCodeAction;
  53489. }(BABYLON.Action));
  53490. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53491. var SetParentAction = /** @class */ (function (_super) {
  53492. __extends(SetParentAction, _super);
  53493. function SetParentAction(triggerOptions, target, parent, condition) {
  53494. var _this = _super.call(this, triggerOptions, condition) || this;
  53495. _this._target = target;
  53496. _this._parent = parent;
  53497. return _this;
  53498. }
  53499. SetParentAction.prototype._prepare = function () {
  53500. };
  53501. SetParentAction.prototype.execute = function () {
  53502. if (this._target.parent === this._parent) {
  53503. return;
  53504. }
  53505. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53506. invertParentWorldMatrix.invert();
  53507. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53508. this._target.parent = this._parent;
  53509. };
  53510. SetParentAction.prototype.serialize = function (parent) {
  53511. return _super.prototype._serialize.call(this, {
  53512. name: "SetParentAction",
  53513. properties: [
  53514. BABYLON.Action._GetTargetProperty(this._target),
  53515. BABYLON.Action._GetTargetProperty(this._parent),
  53516. ]
  53517. }, parent);
  53518. };
  53519. return SetParentAction;
  53520. }(BABYLON.Action));
  53521. BABYLON.SetParentAction = SetParentAction;
  53522. var PlaySoundAction = /** @class */ (function (_super) {
  53523. __extends(PlaySoundAction, _super);
  53524. function PlaySoundAction(triggerOptions, sound, condition) {
  53525. var _this = _super.call(this, triggerOptions, condition) || this;
  53526. _this._sound = sound;
  53527. return _this;
  53528. }
  53529. PlaySoundAction.prototype._prepare = function () {
  53530. };
  53531. PlaySoundAction.prototype.execute = function () {
  53532. if (this._sound !== undefined)
  53533. this._sound.play();
  53534. };
  53535. PlaySoundAction.prototype.serialize = function (parent) {
  53536. return _super.prototype._serialize.call(this, {
  53537. name: "PlaySoundAction",
  53538. properties: [{ name: "sound", value: this._sound.name }]
  53539. }, parent);
  53540. };
  53541. return PlaySoundAction;
  53542. }(BABYLON.Action));
  53543. BABYLON.PlaySoundAction = PlaySoundAction;
  53544. var StopSoundAction = /** @class */ (function (_super) {
  53545. __extends(StopSoundAction, _super);
  53546. function StopSoundAction(triggerOptions, sound, condition) {
  53547. var _this = _super.call(this, triggerOptions, condition) || this;
  53548. _this._sound = sound;
  53549. return _this;
  53550. }
  53551. StopSoundAction.prototype._prepare = function () {
  53552. };
  53553. StopSoundAction.prototype.execute = function () {
  53554. if (this._sound !== undefined)
  53555. this._sound.stop();
  53556. };
  53557. StopSoundAction.prototype.serialize = function (parent) {
  53558. return _super.prototype._serialize.call(this, {
  53559. name: "StopSoundAction",
  53560. properties: [{ name: "sound", value: this._sound.name }]
  53561. }, parent);
  53562. };
  53563. return StopSoundAction;
  53564. }(BABYLON.Action));
  53565. BABYLON.StopSoundAction = StopSoundAction;
  53566. })(BABYLON || (BABYLON = {}));
  53567. //# sourceMappingURL=babylon.directActions.js.map
  53568. var BABYLON;
  53569. (function (BABYLON) {
  53570. var SpriteManager = /** @class */ (function () {
  53571. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53572. if (epsilon === void 0) { epsilon = 0.01; }
  53573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53574. this.name = name;
  53575. this.sprites = new Array();
  53576. this.renderingGroupId = 0;
  53577. this.layerMask = 0x0FFFFFFF;
  53578. this.fogEnabled = true;
  53579. this.isPickable = false;
  53580. /**
  53581. * An event triggered when the manager is disposed.
  53582. */
  53583. this.onDisposeObservable = new BABYLON.Observable();
  53584. this._vertexBuffers = {};
  53585. this._capacity = capacity;
  53586. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53587. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53588. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53589. if (cellSize.width && cellSize.height) {
  53590. this.cellWidth = cellSize.width;
  53591. this.cellHeight = cellSize.height;
  53592. }
  53593. else if (cellSize !== undefined) {
  53594. this.cellWidth = cellSize;
  53595. this.cellHeight = cellSize;
  53596. }
  53597. else {
  53598. return;
  53599. }
  53600. this._epsilon = epsilon;
  53601. this._scene = scene;
  53602. this._scene.spriteManagers.push(this);
  53603. var indices = [];
  53604. var index = 0;
  53605. for (var count = 0; count < capacity; count++) {
  53606. indices.push(index);
  53607. indices.push(index + 1);
  53608. indices.push(index + 2);
  53609. indices.push(index);
  53610. indices.push(index + 2);
  53611. indices.push(index + 3);
  53612. index += 4;
  53613. }
  53614. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53615. // VBO
  53616. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53617. this._vertexData = new Float32Array(capacity * 16 * 4);
  53618. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53619. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53620. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53621. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53622. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53624. this._vertexBuffers["options"] = options;
  53625. this._vertexBuffers["cellInfo"] = cellInfo;
  53626. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53627. // Effects
  53628. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53629. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53630. }
  53631. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53632. set: function (callback) {
  53633. if (this._onDisposeObserver) {
  53634. this.onDisposeObservable.remove(this._onDisposeObserver);
  53635. }
  53636. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53637. },
  53638. enumerable: true,
  53639. configurable: true
  53640. });
  53641. Object.defineProperty(SpriteManager.prototype, "texture", {
  53642. get: function () {
  53643. return this._spriteTexture;
  53644. },
  53645. set: function (value) {
  53646. this._spriteTexture = value;
  53647. },
  53648. enumerable: true,
  53649. configurable: true
  53650. });
  53651. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53652. var arrayOffset = index * 16;
  53653. if (offsetX === 0)
  53654. offsetX = this._epsilon;
  53655. else if (offsetX === 1)
  53656. offsetX = 1 - this._epsilon;
  53657. if (offsetY === 0)
  53658. offsetY = this._epsilon;
  53659. else if (offsetY === 1)
  53660. offsetY = 1 - this._epsilon;
  53661. this._vertexData[arrayOffset] = sprite.position.x;
  53662. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53663. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53664. this._vertexData[arrayOffset + 3] = sprite.angle;
  53665. this._vertexData[arrayOffset + 4] = sprite.width;
  53666. this._vertexData[arrayOffset + 5] = sprite.height;
  53667. this._vertexData[arrayOffset + 6] = offsetX;
  53668. this._vertexData[arrayOffset + 7] = offsetY;
  53669. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53670. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53671. var offset = (sprite.cellIndex / rowSize) >> 0;
  53672. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53673. this._vertexData[arrayOffset + 11] = offset;
  53674. // Color
  53675. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53676. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53677. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53678. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53679. };
  53680. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53681. var count = Math.min(this._capacity, this.sprites.length);
  53682. var min = BABYLON.Vector3.Zero();
  53683. var max = BABYLON.Vector3.Zero();
  53684. var distance = Number.MAX_VALUE;
  53685. var currentSprite = null;
  53686. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53687. var cameraView = camera.getViewMatrix();
  53688. for (var index = 0; index < count; index++) {
  53689. var sprite = this.sprites[index];
  53690. if (!sprite) {
  53691. continue;
  53692. }
  53693. if (predicate) {
  53694. if (!predicate(sprite)) {
  53695. continue;
  53696. }
  53697. }
  53698. else if (!sprite.isPickable) {
  53699. continue;
  53700. }
  53701. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53702. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53703. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53704. if (ray.intersectsBoxMinMax(min, max)) {
  53705. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53706. if (distance > currentDistance) {
  53707. distance = currentDistance;
  53708. currentSprite = sprite;
  53709. if (fastCheck) {
  53710. break;
  53711. }
  53712. }
  53713. }
  53714. }
  53715. if (currentSprite) {
  53716. var result = new BABYLON.PickingInfo();
  53717. result.hit = true;
  53718. result.pickedSprite = currentSprite;
  53719. result.distance = distance;
  53720. return result;
  53721. }
  53722. return null;
  53723. };
  53724. SpriteManager.prototype.render = function () {
  53725. // Check
  53726. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53727. return;
  53728. var engine = this._scene.getEngine();
  53729. var baseSize = this._spriteTexture.getBaseSize();
  53730. // Sprites
  53731. var deltaTime = engine.getDeltaTime();
  53732. var max = Math.min(this._capacity, this.sprites.length);
  53733. var rowSize = baseSize.width / this.cellWidth;
  53734. var offset = 0;
  53735. for (var index = 0; index < max; index++) {
  53736. var sprite = this.sprites[index];
  53737. if (!sprite) {
  53738. continue;
  53739. }
  53740. sprite._animate(deltaTime);
  53741. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53742. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53743. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53744. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53745. }
  53746. this._buffer.update(this._vertexData);
  53747. // Render
  53748. var effect = this._effectBase;
  53749. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53750. effect = this._effectFog;
  53751. }
  53752. engine.enableEffect(effect);
  53753. var viewMatrix = this._scene.getViewMatrix();
  53754. effect.setTexture("diffuseSampler", this._spriteTexture);
  53755. effect.setMatrix("view", viewMatrix);
  53756. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53757. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53758. // Fog
  53759. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53760. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53761. effect.setColor3("vFogColor", this._scene.fogColor);
  53762. }
  53763. // VBOs
  53764. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53765. // Draw order
  53766. engine.setDepthFunctionToLessOrEqual();
  53767. effect.setBool("alphaTest", true);
  53768. engine.setColorWrite(false);
  53769. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53770. engine.setColorWrite(true);
  53771. effect.setBool("alphaTest", false);
  53772. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53773. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53774. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53775. };
  53776. SpriteManager.prototype.dispose = function () {
  53777. if (this._buffer) {
  53778. this._buffer.dispose();
  53779. this._buffer = null;
  53780. }
  53781. if (this._indexBuffer) {
  53782. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53783. this._indexBuffer = null;
  53784. }
  53785. if (this._spriteTexture) {
  53786. this._spriteTexture.dispose();
  53787. this._spriteTexture = null;
  53788. }
  53789. // Remove from scene
  53790. var index = this._scene.spriteManagers.indexOf(this);
  53791. this._scene.spriteManagers.splice(index, 1);
  53792. // Callback
  53793. this.onDisposeObservable.notifyObservers(this);
  53794. this.onDisposeObservable.clear();
  53795. };
  53796. return SpriteManager;
  53797. }());
  53798. BABYLON.SpriteManager = SpriteManager;
  53799. })(BABYLON || (BABYLON = {}));
  53800. //# sourceMappingURL=babylon.spriteManager.js.map
  53801. var BABYLON;
  53802. (function (BABYLON) {
  53803. var Sprite = /** @class */ (function () {
  53804. function Sprite(name, manager) {
  53805. this.name = name;
  53806. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53807. this.width = 1.0;
  53808. this.height = 1.0;
  53809. this.angle = 0;
  53810. this.cellIndex = 0;
  53811. this.invertU = 0;
  53812. this.invertV = 0;
  53813. this.animations = new Array();
  53814. this.isPickable = false;
  53815. this._animationStarted = false;
  53816. this._loopAnimation = false;
  53817. this._fromIndex = 0;
  53818. this._toIndex = 0;
  53819. this._delay = 0;
  53820. this._direction = 1;
  53821. this._time = 0;
  53822. this._manager = manager;
  53823. this._manager.sprites.push(this);
  53824. this.position = BABYLON.Vector3.Zero();
  53825. }
  53826. Object.defineProperty(Sprite.prototype, "size", {
  53827. get: function () {
  53828. return this.width;
  53829. },
  53830. set: function (value) {
  53831. this.width = value;
  53832. this.height = value;
  53833. },
  53834. enumerable: true,
  53835. configurable: true
  53836. });
  53837. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53838. this._fromIndex = from;
  53839. this._toIndex = to;
  53840. this._loopAnimation = loop;
  53841. this._delay = delay;
  53842. this._animationStarted = true;
  53843. this._direction = from < to ? 1 : -1;
  53844. this.cellIndex = from;
  53845. this._time = 0;
  53846. this._onAnimationEnd = onAnimationEnd;
  53847. };
  53848. Sprite.prototype.stopAnimation = function () {
  53849. this._animationStarted = false;
  53850. };
  53851. Sprite.prototype._animate = function (deltaTime) {
  53852. if (!this._animationStarted)
  53853. return;
  53854. this._time += deltaTime;
  53855. if (this._time > this._delay) {
  53856. this._time = this._time % this._delay;
  53857. this.cellIndex += this._direction;
  53858. if (this.cellIndex > this._toIndex) {
  53859. if (this._loopAnimation) {
  53860. this.cellIndex = this._fromIndex;
  53861. }
  53862. else {
  53863. this.cellIndex = this._toIndex;
  53864. this._animationStarted = false;
  53865. if (this._onAnimationEnd) {
  53866. this._onAnimationEnd();
  53867. }
  53868. if (this.disposeWhenFinishedAnimating) {
  53869. this.dispose();
  53870. }
  53871. }
  53872. }
  53873. }
  53874. };
  53875. Sprite.prototype.dispose = function () {
  53876. for (var i = 0; i < this._manager.sprites.length; i++) {
  53877. if (this._manager.sprites[i] == this) {
  53878. this._manager.sprites.splice(i, 1);
  53879. }
  53880. }
  53881. };
  53882. return Sprite;
  53883. }());
  53884. BABYLON.Sprite = Sprite;
  53885. })(BABYLON || (BABYLON = {}));
  53886. //# sourceMappingURL=babylon.sprite.js.map
  53887. var BABYLON;
  53888. (function (BABYLON) {
  53889. var IntersectionInfo = /** @class */ (function () {
  53890. function IntersectionInfo(bu, bv, distance) {
  53891. this.bu = bu;
  53892. this.bv = bv;
  53893. this.distance = distance;
  53894. this.faceId = 0;
  53895. this.subMeshId = 0;
  53896. }
  53897. return IntersectionInfo;
  53898. }());
  53899. BABYLON.IntersectionInfo = IntersectionInfo;
  53900. var PickingInfo = /** @class */ (function () {
  53901. function PickingInfo() {
  53902. this.hit = false;
  53903. this.distance = 0;
  53904. this.pickedPoint = null;
  53905. this.pickedMesh = null;
  53906. this.bu = 0;
  53907. this.bv = 0;
  53908. this.faceId = -1;
  53909. this.subMeshId = 0;
  53910. this.pickedSprite = null;
  53911. }
  53912. // Methods
  53913. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53914. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53915. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53916. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53917. return null;
  53918. }
  53919. var indices = this.pickedMesh.getIndices();
  53920. if (!indices) {
  53921. return null;
  53922. }
  53923. var result;
  53924. if (useVerticesNormals) {
  53925. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53926. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53927. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53928. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53929. normal0 = normal0.scale(this.bu);
  53930. normal1 = normal1.scale(this.bv);
  53931. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53932. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53933. }
  53934. else {
  53935. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53936. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53937. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53938. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53939. var p1p2 = vertex1.subtract(vertex2);
  53940. var p3p2 = vertex3.subtract(vertex2);
  53941. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53942. }
  53943. if (useWorldCoordinates) {
  53944. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53945. }
  53946. return BABYLON.Vector3.Normalize(result);
  53947. };
  53948. PickingInfo.prototype.getTextureCoordinates = function () {
  53949. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53950. return null;
  53951. }
  53952. var indices = this.pickedMesh.getIndices();
  53953. if (!indices) {
  53954. return null;
  53955. }
  53956. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53957. if (!uvs) {
  53958. return null;
  53959. }
  53960. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53961. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53962. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53963. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53964. uv1 = uv1.scale(this.bu);
  53965. uv2 = uv2.scale(this.bv);
  53966. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53967. };
  53968. return PickingInfo;
  53969. }());
  53970. BABYLON.PickingInfo = PickingInfo;
  53971. })(BABYLON || (BABYLON = {}));
  53972. //# sourceMappingURL=babylon.pickingInfo.js.map
  53973. var BABYLON;
  53974. (function (BABYLON) {
  53975. var Ray = /** @class */ (function () {
  53976. function Ray(origin, direction, length) {
  53977. if (length === void 0) { length = Number.MAX_VALUE; }
  53978. this.origin = origin;
  53979. this.direction = direction;
  53980. this.length = length;
  53981. }
  53982. // Methods
  53983. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53984. var d = 0.0;
  53985. var maxValue = Number.MAX_VALUE;
  53986. var inv;
  53987. var min;
  53988. var max;
  53989. var temp;
  53990. if (Math.abs(this.direction.x) < 0.0000001) {
  53991. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53992. return false;
  53993. }
  53994. }
  53995. else {
  53996. inv = 1.0 / this.direction.x;
  53997. min = (minimum.x - this.origin.x) * inv;
  53998. max = (maximum.x - this.origin.x) * inv;
  53999. if (max === -Infinity) {
  54000. max = Infinity;
  54001. }
  54002. if (min > max) {
  54003. temp = min;
  54004. min = max;
  54005. max = temp;
  54006. }
  54007. d = Math.max(min, d);
  54008. maxValue = Math.min(max, maxValue);
  54009. if (d > maxValue) {
  54010. return false;
  54011. }
  54012. }
  54013. if (Math.abs(this.direction.y) < 0.0000001) {
  54014. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54015. return false;
  54016. }
  54017. }
  54018. else {
  54019. inv = 1.0 / this.direction.y;
  54020. min = (minimum.y - this.origin.y) * inv;
  54021. max = (maximum.y - this.origin.y) * inv;
  54022. if (max === -Infinity) {
  54023. max = Infinity;
  54024. }
  54025. if (min > max) {
  54026. temp = min;
  54027. min = max;
  54028. max = temp;
  54029. }
  54030. d = Math.max(min, d);
  54031. maxValue = Math.min(max, maxValue);
  54032. if (d > maxValue) {
  54033. return false;
  54034. }
  54035. }
  54036. if (Math.abs(this.direction.z) < 0.0000001) {
  54037. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54038. return false;
  54039. }
  54040. }
  54041. else {
  54042. inv = 1.0 / this.direction.z;
  54043. min = (minimum.z - this.origin.z) * inv;
  54044. max = (maximum.z - this.origin.z) * inv;
  54045. if (max === -Infinity) {
  54046. max = Infinity;
  54047. }
  54048. if (min > max) {
  54049. temp = min;
  54050. min = max;
  54051. max = temp;
  54052. }
  54053. d = Math.max(min, d);
  54054. maxValue = Math.min(max, maxValue);
  54055. if (d > maxValue) {
  54056. return false;
  54057. }
  54058. }
  54059. return true;
  54060. };
  54061. Ray.prototype.intersectsBox = function (box) {
  54062. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54063. };
  54064. Ray.prototype.intersectsSphere = function (sphere) {
  54065. var x = sphere.center.x - this.origin.x;
  54066. var y = sphere.center.y - this.origin.y;
  54067. var z = sphere.center.z - this.origin.z;
  54068. var pyth = (x * x) + (y * y) + (z * z);
  54069. var rr = sphere.radius * sphere.radius;
  54070. if (pyth <= rr) {
  54071. return true;
  54072. }
  54073. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54074. if (dot < 0.0) {
  54075. return false;
  54076. }
  54077. var temp = pyth - (dot * dot);
  54078. return temp <= rr;
  54079. };
  54080. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54081. if (!this._edge1) {
  54082. this._edge1 = BABYLON.Vector3.Zero();
  54083. this._edge2 = BABYLON.Vector3.Zero();
  54084. this._pvec = BABYLON.Vector3.Zero();
  54085. this._tvec = BABYLON.Vector3.Zero();
  54086. this._qvec = BABYLON.Vector3.Zero();
  54087. }
  54088. vertex1.subtractToRef(vertex0, this._edge1);
  54089. vertex2.subtractToRef(vertex0, this._edge2);
  54090. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54091. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54092. if (det === 0) {
  54093. return null;
  54094. }
  54095. var invdet = 1 / det;
  54096. this.origin.subtractToRef(vertex0, this._tvec);
  54097. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54098. if (bu < 0 || bu > 1.0) {
  54099. return null;
  54100. }
  54101. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54102. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54103. if (bv < 0 || bu + bv > 1.0) {
  54104. return null;
  54105. }
  54106. //check if the distance is longer than the predefined length.
  54107. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54108. if (distance > this.length) {
  54109. return null;
  54110. }
  54111. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54112. };
  54113. Ray.prototype.intersectsPlane = function (plane) {
  54114. var distance;
  54115. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54116. if (Math.abs(result1) < 9.99999997475243E-07) {
  54117. return null;
  54118. }
  54119. else {
  54120. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54121. distance = (-plane.d - result2) / result1;
  54122. if (distance < 0.0) {
  54123. if (distance < -9.99999997475243E-07) {
  54124. return null;
  54125. }
  54126. else {
  54127. return 0;
  54128. }
  54129. }
  54130. return distance;
  54131. }
  54132. };
  54133. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54134. var tm = BABYLON.Tmp.Matrix[0];
  54135. mesh.getWorldMatrix().invertToRef(tm);
  54136. if (this._tmpRay) {
  54137. Ray.TransformToRef(this, tm, this._tmpRay);
  54138. }
  54139. else {
  54140. this._tmpRay = Ray.Transform(this, tm);
  54141. }
  54142. return mesh.intersects(this._tmpRay, fastCheck);
  54143. };
  54144. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54145. if (results) {
  54146. results.length = 0;
  54147. }
  54148. else {
  54149. results = [];
  54150. }
  54151. for (var i = 0; i < meshes.length; i++) {
  54152. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54153. if (pickInfo.hit) {
  54154. results.push(pickInfo);
  54155. }
  54156. }
  54157. results.sort(this._comparePickingInfo);
  54158. return results;
  54159. };
  54160. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54161. if (pickingInfoA.distance < pickingInfoB.distance) {
  54162. return -1;
  54163. }
  54164. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54165. return 1;
  54166. }
  54167. else {
  54168. return 0;
  54169. }
  54170. };
  54171. /**
  54172. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54173. * @param sega the first point of the segment to test the intersection against
  54174. * @param segb the second point of the segment to test the intersection against
  54175. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54176. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54177. */
  54178. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54179. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54180. var u = segb.subtract(sega);
  54181. var v = rsegb.subtract(this.origin);
  54182. var w = sega.subtract(this.origin);
  54183. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54184. var b = BABYLON.Vector3.Dot(u, v);
  54185. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54186. var d = BABYLON.Vector3.Dot(u, w);
  54187. var e = BABYLON.Vector3.Dot(v, w);
  54188. var D = a * c - b * b; // always >= 0
  54189. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54190. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54191. // compute the line parameters of the two closest points
  54192. if (D < Ray.smallnum) { // the lines are almost parallel
  54193. sN = 0.0; // force using point P0 on segment S1
  54194. sD = 1.0; // to prevent possible division by 0.0 later
  54195. tN = e;
  54196. tD = c;
  54197. }
  54198. else { // get the closest points on the infinite lines
  54199. sN = (b * e - c * d);
  54200. tN = (a * e - b * d);
  54201. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54202. sN = 0.0;
  54203. tN = e;
  54204. tD = c;
  54205. }
  54206. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54207. sN = sD;
  54208. tN = e + b;
  54209. tD = c;
  54210. }
  54211. }
  54212. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54213. tN = 0.0;
  54214. // recompute sc for this edge
  54215. if (-d < 0.0) {
  54216. sN = 0.0;
  54217. }
  54218. else if (-d > a)
  54219. sN = sD;
  54220. else {
  54221. sN = -d;
  54222. sD = a;
  54223. }
  54224. }
  54225. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54226. tN = tD;
  54227. // recompute sc for this edge
  54228. if ((-d + b) < 0.0) {
  54229. sN = 0;
  54230. }
  54231. else if ((-d + b) > a) {
  54232. sN = sD;
  54233. }
  54234. else {
  54235. sN = (-d + b);
  54236. sD = a;
  54237. }
  54238. }
  54239. // finally do the division to get sc and tc
  54240. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54241. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54242. // get the difference of the two closest points
  54243. var qtc = v.multiplyByFloats(tc, tc, tc);
  54244. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54245. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54246. if (isIntersected) {
  54247. return qtc.length();
  54248. }
  54249. return -1;
  54250. };
  54251. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54252. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54253. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54254. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54255. this.direction.normalize();
  54256. return this;
  54257. };
  54258. // Statics
  54259. Ray.Zero = function () {
  54260. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54261. };
  54262. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54263. var result = Ray.Zero();
  54264. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54265. };
  54266. /**
  54267. * 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
  54268. * transformed to the given world matrix.
  54269. * @param origin The origin point
  54270. * @param end The end point
  54271. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54272. */
  54273. Ray.CreateNewFromTo = function (origin, end, world) {
  54274. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54275. var direction = end.subtract(origin);
  54276. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54277. direction.normalize();
  54278. return Ray.Transform(new Ray(origin, direction, length), world);
  54279. };
  54280. Ray.Transform = function (ray, matrix) {
  54281. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54282. Ray.TransformToRef(ray, matrix, result);
  54283. return result;
  54284. };
  54285. Ray.TransformToRef = function (ray, matrix, result) {
  54286. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54287. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54288. result.length = ray.length;
  54289. var dir = result.direction;
  54290. var len = dir.length();
  54291. if (!(len === 0 || len === 1)) {
  54292. var num = 1.0 / len;
  54293. dir.x *= num;
  54294. dir.y *= num;
  54295. dir.z *= num;
  54296. result.length *= len;
  54297. }
  54298. };
  54299. Ray.smallnum = 0.00000001;
  54300. Ray.rayl = 10e8;
  54301. return Ray;
  54302. }());
  54303. BABYLON.Ray = Ray;
  54304. })(BABYLON || (BABYLON = {}));
  54305. //# sourceMappingURL=babylon.ray.js.map
  54306. var BABYLON;
  54307. (function (BABYLON) {
  54308. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54309. if (boxMin.x > sphereCenter.x + sphereRadius)
  54310. return false;
  54311. if (sphereCenter.x - sphereRadius > boxMax.x)
  54312. return false;
  54313. if (boxMin.y > sphereCenter.y + sphereRadius)
  54314. return false;
  54315. if (sphereCenter.y - sphereRadius > boxMax.y)
  54316. return false;
  54317. if (boxMin.z > sphereCenter.z + sphereRadius)
  54318. return false;
  54319. if (sphereCenter.z - sphereRadius > boxMax.z)
  54320. return false;
  54321. return true;
  54322. };
  54323. var getLowestRoot = (function () {
  54324. var result = { root: 0, found: false };
  54325. return function (a, b, c, maxR) {
  54326. result.root = 0;
  54327. result.found = false;
  54328. var determinant = b * b - 4.0 * a * c;
  54329. if (determinant < 0)
  54330. return result;
  54331. var sqrtD = Math.sqrt(determinant);
  54332. var r1 = (-b - sqrtD) / (2.0 * a);
  54333. var r2 = (-b + sqrtD) / (2.0 * a);
  54334. if (r1 > r2) {
  54335. var temp = r2;
  54336. r2 = r1;
  54337. r1 = temp;
  54338. }
  54339. if (r1 > 0 && r1 < maxR) {
  54340. result.root = r1;
  54341. result.found = true;
  54342. return result;
  54343. }
  54344. if (r2 > 0 && r2 < maxR) {
  54345. result.root = r2;
  54346. result.found = true;
  54347. return result;
  54348. }
  54349. return result;
  54350. };
  54351. })();
  54352. var Collider = /** @class */ (function () {
  54353. function Collider() {
  54354. this._collisionPoint = BABYLON.Vector3.Zero();
  54355. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54356. this._tempVector = BABYLON.Vector3.Zero();
  54357. this._tempVector2 = BABYLON.Vector3.Zero();
  54358. this._tempVector3 = BABYLON.Vector3.Zero();
  54359. this._tempVector4 = BABYLON.Vector3.Zero();
  54360. this._edge = BABYLON.Vector3.Zero();
  54361. this._baseToVertex = BABYLON.Vector3.Zero();
  54362. this._destinationPoint = BABYLON.Vector3.Zero();
  54363. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54364. this._displacementVector = BABYLON.Vector3.Zero();
  54365. this._radius = BABYLON.Vector3.One();
  54366. this._retry = 0;
  54367. this._basePointWorld = BABYLON.Vector3.Zero();
  54368. this._velocityWorld = BABYLON.Vector3.Zero();
  54369. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54370. this._collisionMask = -1;
  54371. }
  54372. Object.defineProperty(Collider.prototype, "collisionMask", {
  54373. get: function () {
  54374. return this._collisionMask;
  54375. },
  54376. set: function (mask) {
  54377. this._collisionMask = !isNaN(mask) ? mask : -1;
  54378. },
  54379. enumerable: true,
  54380. configurable: true
  54381. });
  54382. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54383. /**
  54384. * Gets the plane normal used to compute the sliding response (in local space)
  54385. */
  54386. get: function () {
  54387. return this._slidePlaneNormal;
  54388. },
  54389. enumerable: true,
  54390. configurable: true
  54391. });
  54392. // Methods
  54393. Collider.prototype._initialize = function (source, dir, e) {
  54394. this._velocity = dir;
  54395. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54396. this._basePoint = source;
  54397. source.multiplyToRef(this._radius, this._basePointWorld);
  54398. dir.multiplyToRef(this._radius, this._velocityWorld);
  54399. this._velocityWorldLength = this._velocityWorld.length();
  54400. this._epsilon = e;
  54401. this.collisionFound = false;
  54402. };
  54403. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54404. pa.subtractToRef(point, this._tempVector);
  54405. pb.subtractToRef(point, this._tempVector2);
  54406. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54407. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54408. if (d < 0)
  54409. return false;
  54410. pc.subtractToRef(point, this._tempVector3);
  54411. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54412. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54413. if (d < 0)
  54414. return false;
  54415. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54416. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54417. return d >= 0;
  54418. };
  54419. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54420. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54421. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54422. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54423. return false;
  54424. }
  54425. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54426. return false;
  54427. return true;
  54428. };
  54429. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54430. var t0;
  54431. var embeddedInPlane = false;
  54432. //defensive programming, actually not needed.
  54433. if (!trianglePlaneArray) {
  54434. trianglePlaneArray = [];
  54435. }
  54436. if (!trianglePlaneArray[faceIndex]) {
  54437. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54438. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54439. }
  54440. var trianglePlane = trianglePlaneArray[faceIndex];
  54441. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54442. return;
  54443. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54444. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54445. if (normalDotVelocity == 0) {
  54446. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54447. return;
  54448. embeddedInPlane = true;
  54449. t0 = 0;
  54450. }
  54451. else {
  54452. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54453. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54454. if (t0 > t1) {
  54455. var temp = t1;
  54456. t1 = t0;
  54457. t0 = temp;
  54458. }
  54459. if (t0 > 1.0 || t1 < 0.0)
  54460. return;
  54461. if (t0 < 0)
  54462. t0 = 0;
  54463. if (t0 > 1.0)
  54464. t0 = 1.0;
  54465. }
  54466. this._collisionPoint.copyFromFloats(0, 0, 0);
  54467. var found = false;
  54468. var t = 1.0;
  54469. if (!embeddedInPlane) {
  54470. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54471. this._velocity.scaleToRef(t0, this._tempVector);
  54472. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54473. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54474. found = true;
  54475. t = t0;
  54476. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54477. }
  54478. }
  54479. if (!found) {
  54480. var velocitySquaredLength = this._velocity.lengthSquared();
  54481. var a = velocitySquaredLength;
  54482. this._basePoint.subtractToRef(p1, this._tempVector);
  54483. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54484. var c = this._tempVector.lengthSquared() - 1.0;
  54485. var lowestRoot = getLowestRoot(a, b, c, t);
  54486. if (lowestRoot.found) {
  54487. t = lowestRoot.root;
  54488. found = true;
  54489. this._collisionPoint.copyFrom(p1);
  54490. }
  54491. this._basePoint.subtractToRef(p2, this._tempVector);
  54492. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54493. c = this._tempVector.lengthSquared() - 1.0;
  54494. lowestRoot = getLowestRoot(a, b, c, t);
  54495. if (lowestRoot.found) {
  54496. t = lowestRoot.root;
  54497. found = true;
  54498. this._collisionPoint.copyFrom(p2);
  54499. }
  54500. this._basePoint.subtractToRef(p3, this._tempVector);
  54501. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54502. c = this._tempVector.lengthSquared() - 1.0;
  54503. lowestRoot = getLowestRoot(a, b, c, t);
  54504. if (lowestRoot.found) {
  54505. t = lowestRoot.root;
  54506. found = true;
  54507. this._collisionPoint.copyFrom(p3);
  54508. }
  54509. p2.subtractToRef(p1, this._edge);
  54510. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54511. var edgeSquaredLength = this._edge.lengthSquared();
  54512. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54513. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54514. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54515. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54516. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54517. lowestRoot = getLowestRoot(a, b, c, t);
  54518. if (lowestRoot.found) {
  54519. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54520. if (f >= 0.0 && f <= 1.0) {
  54521. t = lowestRoot.root;
  54522. found = true;
  54523. this._edge.scaleInPlace(f);
  54524. p1.addToRef(this._edge, this._collisionPoint);
  54525. }
  54526. }
  54527. p3.subtractToRef(p2, this._edge);
  54528. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54529. edgeSquaredLength = this._edge.lengthSquared();
  54530. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54531. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54532. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54533. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54534. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54535. lowestRoot = getLowestRoot(a, b, c, t);
  54536. if (lowestRoot.found) {
  54537. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54538. if (f >= 0.0 && f <= 1.0) {
  54539. t = lowestRoot.root;
  54540. found = true;
  54541. this._edge.scaleInPlace(f);
  54542. p2.addToRef(this._edge, this._collisionPoint);
  54543. }
  54544. }
  54545. p1.subtractToRef(p3, this._edge);
  54546. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54547. edgeSquaredLength = this._edge.lengthSquared();
  54548. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54549. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54550. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54551. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54552. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54553. lowestRoot = getLowestRoot(a, b, c, t);
  54554. if (lowestRoot.found) {
  54555. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54556. if (f >= 0.0 && f <= 1.0) {
  54557. t = lowestRoot.root;
  54558. found = true;
  54559. this._edge.scaleInPlace(f);
  54560. p3.addToRef(this._edge, this._collisionPoint);
  54561. }
  54562. }
  54563. }
  54564. if (found) {
  54565. var distToCollision = t * this._velocity.length();
  54566. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54567. if (!this.intersectionPoint) {
  54568. this.intersectionPoint = this._collisionPoint.clone();
  54569. }
  54570. else {
  54571. this.intersectionPoint.copyFrom(this._collisionPoint);
  54572. }
  54573. this._nearestDistance = distToCollision;
  54574. this.collisionFound = true;
  54575. }
  54576. }
  54577. };
  54578. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54579. for (var i = indexStart; i < indexEnd; i += 3) {
  54580. var p1 = pts[indices[i] - decal];
  54581. var p2 = pts[indices[i + 1] - decal];
  54582. var p3 = pts[indices[i + 2] - decal];
  54583. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54584. }
  54585. };
  54586. Collider.prototype._getResponse = function (pos, vel) {
  54587. pos.addToRef(vel, this._destinationPoint);
  54588. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54589. this._basePoint.addToRef(vel, pos);
  54590. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54591. this._slidePlaneNormal.normalize();
  54592. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54593. pos.addInPlace(this._displacementVector);
  54594. this.intersectionPoint.addInPlace(this._displacementVector);
  54595. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54596. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54597. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54598. };
  54599. return Collider;
  54600. }());
  54601. BABYLON.Collider = Collider;
  54602. })(BABYLON || (BABYLON = {}));
  54603. //# sourceMappingURL=babylon.collider.js.map
  54604. var BABYLON;
  54605. (function (BABYLON) {
  54606. //WebWorker code will be inserted to this variable.
  54607. BABYLON.CollisionWorker = "";
  54608. /** Defines supported task for worker process */
  54609. var WorkerTaskType;
  54610. (function (WorkerTaskType) {
  54611. /** Initialization */
  54612. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54613. /** Update of geometry */
  54614. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54615. /** Evaluate collision */
  54616. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54617. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54618. /** Defines kind of replies returned by worker */
  54619. var WorkerReplyType;
  54620. (function (WorkerReplyType) {
  54621. /** Success */
  54622. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54623. /** Unkown error */
  54624. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54625. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54626. var CollisionCoordinatorWorker = /** @class */ (function () {
  54627. function CollisionCoordinatorWorker() {
  54628. var _this = this;
  54629. this._scaledPosition = BABYLON.Vector3.Zero();
  54630. this._scaledVelocity = BABYLON.Vector3.Zero();
  54631. this.onMeshUpdated = function (transformNode) {
  54632. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54633. };
  54634. this.onGeometryUpdated = function (geometry) {
  54635. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54636. };
  54637. this._afterRender = function () {
  54638. if (!_this._init)
  54639. return;
  54640. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54641. return;
  54642. }
  54643. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54644. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54645. if (_this._runningUpdated > 4) {
  54646. return;
  54647. }
  54648. ++_this._runningUpdated;
  54649. var payload = {
  54650. updatedMeshes: _this._addUpdateMeshesList,
  54651. updatedGeometries: _this._addUpdateGeometriesList,
  54652. removedGeometries: _this._toRemoveGeometryArray,
  54653. removedMeshes: _this._toRemoveMeshesArray
  54654. };
  54655. var message = {
  54656. payload: payload,
  54657. taskType: WorkerTaskType.UPDATE
  54658. };
  54659. var serializable = [];
  54660. for (var id in payload.updatedGeometries) {
  54661. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54662. //prepare transferables
  54663. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54664. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54665. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54666. }
  54667. }
  54668. _this._worker.postMessage(message, serializable);
  54669. _this._addUpdateMeshesList = {};
  54670. _this._addUpdateGeometriesList = {};
  54671. _this._toRemoveGeometryArray = [];
  54672. _this._toRemoveMeshesArray = [];
  54673. };
  54674. this._onMessageFromWorker = function (e) {
  54675. var returnData = e.data;
  54676. if (returnData.error != WorkerReplyType.SUCCESS) {
  54677. //TODO what errors can be returned from the worker?
  54678. BABYLON.Tools.Warn("error returned from worker!");
  54679. return;
  54680. }
  54681. switch (returnData.taskType) {
  54682. case WorkerTaskType.INIT:
  54683. _this._init = true;
  54684. //Update the worked with ALL of the scene's current state
  54685. _this._scene.meshes.forEach(function (mesh) {
  54686. _this.onMeshAdded(mesh);
  54687. });
  54688. _this._scene.getGeometries().forEach(function (geometry) {
  54689. _this.onGeometryAdded(geometry);
  54690. });
  54691. break;
  54692. case WorkerTaskType.UPDATE:
  54693. _this._runningUpdated--;
  54694. break;
  54695. case WorkerTaskType.COLLIDE:
  54696. var returnPayload = returnData.payload;
  54697. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54698. return;
  54699. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54700. if (callback) {
  54701. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54702. if (mesh) {
  54703. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54704. }
  54705. }
  54706. //cleanup
  54707. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54708. break;
  54709. }
  54710. };
  54711. this._collisionsCallbackArray = [];
  54712. this._init = false;
  54713. this._runningUpdated = 0;
  54714. this._addUpdateMeshesList = {};
  54715. this._addUpdateGeometriesList = {};
  54716. this._toRemoveGeometryArray = [];
  54717. this._toRemoveMeshesArray = [];
  54718. }
  54719. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54720. if (!this._init)
  54721. return;
  54722. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54723. return;
  54724. position.divideToRef(collider._radius, this._scaledPosition);
  54725. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54726. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54727. var payload = {
  54728. collider: {
  54729. position: this._scaledPosition.asArray(),
  54730. velocity: this._scaledVelocity.asArray(),
  54731. radius: collider._radius.asArray()
  54732. },
  54733. collisionId: collisionIndex,
  54734. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54735. maximumRetry: maximumRetry
  54736. };
  54737. var message = {
  54738. payload: payload,
  54739. taskType: WorkerTaskType.COLLIDE
  54740. };
  54741. this._worker.postMessage(message);
  54742. };
  54743. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54744. this._scene = scene;
  54745. this._scene.registerAfterRender(this._afterRender);
  54746. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54747. this._worker = new Worker(workerUrl);
  54748. this._worker.onmessage = this._onMessageFromWorker;
  54749. var message = {
  54750. payload: {},
  54751. taskType: WorkerTaskType.INIT
  54752. };
  54753. this._worker.postMessage(message);
  54754. };
  54755. CollisionCoordinatorWorker.prototype.destroy = function () {
  54756. this._scene.unregisterAfterRender(this._afterRender);
  54757. this._worker.terminate();
  54758. };
  54759. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54760. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54761. this.onMeshUpdated(mesh);
  54762. };
  54763. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54764. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54765. };
  54766. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54767. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54768. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54769. this.onGeometryUpdated(geometry);
  54770. };
  54771. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54772. this._toRemoveGeometryArray.push(geometry.id);
  54773. };
  54774. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54775. var submeshes = [];
  54776. if (mesh.subMeshes) {
  54777. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54778. var boundingInfo = sm.getBoundingInfo();
  54779. return {
  54780. position: idx,
  54781. verticesStart: sm.verticesStart,
  54782. verticesCount: sm.verticesCount,
  54783. indexStart: sm.indexStart,
  54784. indexCount: sm.indexCount,
  54785. hasMaterial: !!sm.getMaterial(),
  54786. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54787. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54788. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54789. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54790. };
  54791. });
  54792. }
  54793. var geometryId = null;
  54794. if (mesh instanceof BABYLON.Mesh) {
  54795. var geometry = mesh.geometry;
  54796. geometryId = geometry ? geometry.id : null;
  54797. }
  54798. else if (mesh instanceof BABYLON.InstancedMesh) {
  54799. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54800. geometryId = geometry ? geometry.id : null;
  54801. }
  54802. var boundingInfo = mesh.getBoundingInfo();
  54803. return {
  54804. uniqueId: mesh.uniqueId,
  54805. id: mesh.id,
  54806. name: mesh.name,
  54807. geometryId: geometryId,
  54808. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54809. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54810. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54811. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54812. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54813. subMeshes: submeshes,
  54814. checkCollisions: mesh.checkCollisions
  54815. };
  54816. };
  54817. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54818. return {
  54819. id: geometry.id,
  54820. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54821. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54822. indices: new Uint32Array(geometry.getIndices() || []),
  54823. };
  54824. };
  54825. return CollisionCoordinatorWorker;
  54826. }());
  54827. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54828. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54829. function CollisionCoordinatorLegacy() {
  54830. this._scaledPosition = BABYLON.Vector3.Zero();
  54831. this._scaledVelocity = BABYLON.Vector3.Zero();
  54832. this._finalPosition = BABYLON.Vector3.Zero();
  54833. }
  54834. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54835. position.divideToRef(collider._radius, this._scaledPosition);
  54836. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54837. collider.collidedMesh = null;
  54838. collider._retry = 0;
  54839. collider._initialVelocity = this._scaledVelocity;
  54840. collider._initialPosition = this._scaledPosition;
  54841. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54842. this._finalPosition.multiplyInPlace(collider._radius);
  54843. //run the callback
  54844. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54845. };
  54846. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54847. this._scene = scene;
  54848. };
  54849. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54850. //Legacy need no destruction method.
  54851. };
  54852. //No update in legacy mode
  54853. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54854. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54855. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54856. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54857. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54858. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54859. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54860. if (excludedMesh === void 0) { excludedMesh = null; }
  54861. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54862. if (collider._retry >= maximumRetry) {
  54863. finalPosition.copyFrom(position);
  54864. return;
  54865. }
  54866. // Check if this is a mesh else camera or -1
  54867. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54868. collider._initialize(position, velocity, closeDistance);
  54869. // Check all meshes
  54870. for (var index = 0; index < this._scene.meshes.length; index++) {
  54871. var mesh = this._scene.meshes[index];
  54872. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54873. mesh._checkCollision(collider);
  54874. }
  54875. }
  54876. if (!collider.collisionFound) {
  54877. position.addToRef(velocity, finalPosition);
  54878. return;
  54879. }
  54880. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54881. collider._getResponse(position, velocity);
  54882. }
  54883. if (velocity.length() <= closeDistance) {
  54884. finalPosition.copyFrom(position);
  54885. return;
  54886. }
  54887. collider._retry++;
  54888. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54889. };
  54890. return CollisionCoordinatorLegacy;
  54891. }());
  54892. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54893. })(BABYLON || (BABYLON = {}));
  54894. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54895. var BABYLON;
  54896. (function (BABYLON) {
  54897. /**
  54898. * A particle represents one of the element emitted by a particle system.
  54899. * This is mainly define by its coordinates, direction, velocity and age.
  54900. */
  54901. var Particle = /** @class */ (function () {
  54902. /**
  54903. * Creates a new instance Particle
  54904. * @param particleSystem the particle system the particle belongs to
  54905. */
  54906. function Particle(
  54907. /**
  54908. * particleSystem the particle system the particle belongs to.
  54909. */
  54910. particleSystem) {
  54911. this.particleSystem = particleSystem;
  54912. /**
  54913. * The world position of the particle in the scene.
  54914. */
  54915. this.position = BABYLON.Vector3.Zero();
  54916. /**
  54917. * The world direction of the particle in the scene.
  54918. */
  54919. this.direction = BABYLON.Vector3.Zero();
  54920. /**
  54921. * The color of the particle.
  54922. */
  54923. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54924. /**
  54925. * The color change of the particle per step.
  54926. */
  54927. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54928. /**
  54929. * Defines how long will the life of the particle be.
  54930. */
  54931. this.lifeTime = 1.0;
  54932. /**
  54933. * The current age of the particle.
  54934. */
  54935. this.age = 0;
  54936. /**
  54937. * The current size of the particle.
  54938. */
  54939. this.size = 0;
  54940. /**
  54941. * The current angle of the particle.
  54942. */
  54943. this.angle = 0;
  54944. /**
  54945. * Defines how fast is the angle changing.
  54946. */
  54947. this.angularSpeed = 0;
  54948. /**
  54949. * Defines the cell index used by the particle to be rendered from a sprite.
  54950. */
  54951. this.cellIndex = 0;
  54952. this._currentFrameCounter = 0;
  54953. if (!this.particleSystem.isAnimationSheetEnabled) {
  54954. return;
  54955. }
  54956. this.updateCellInfoFromSystem();
  54957. }
  54958. Particle.prototype.updateCellInfoFromSystem = function () {
  54959. this.cellIndex = this.particleSystem.startSpriteCellID;
  54960. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54961. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54962. }
  54963. else {
  54964. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54965. }
  54966. };
  54967. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54968. // (ageOffset / scaledUpdateSpeed) / available cells
  54969. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54970. this._currentFrameCounter += scaledUpdateSpeed;
  54971. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54972. this._currentFrameCounter = 0;
  54973. this.cellIndex++;
  54974. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54975. this.cellIndex = this.particleSystem.endSpriteCellID;
  54976. }
  54977. }
  54978. };
  54979. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54980. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54981. this.cellIndex++;
  54982. this._currentFrameCounter = 0;
  54983. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54984. if (this.particleSystem.spriteCellLoop) {
  54985. this.cellIndex = this.particleSystem.startSpriteCellID;
  54986. }
  54987. else {
  54988. this.cellIndex = this.particleSystem.endSpriteCellID;
  54989. }
  54990. }
  54991. }
  54992. else {
  54993. this._currentFrameCounter++;
  54994. }
  54995. };
  54996. /**
  54997. * Copy the properties of particle to another one.
  54998. * @param other the particle to copy the information to.
  54999. */
  55000. Particle.prototype.copyTo = function (other) {
  55001. other.position.copyFrom(this.position);
  55002. other.direction.copyFrom(this.direction);
  55003. other.color.copyFrom(this.color);
  55004. other.colorStep.copyFrom(this.colorStep);
  55005. other.lifeTime = this.lifeTime;
  55006. other.age = this.age;
  55007. other.size = this.size;
  55008. other.angle = this.angle;
  55009. other.angularSpeed = this.angularSpeed;
  55010. other.particleSystem = this.particleSystem;
  55011. other.cellIndex = this.cellIndex;
  55012. };
  55013. return Particle;
  55014. }());
  55015. BABYLON.Particle = Particle;
  55016. })(BABYLON || (BABYLON = {}));
  55017. //# sourceMappingURL=babylon.particle.js.map
  55018. var BABYLON;
  55019. (function (BABYLON) {
  55020. /**
  55021. * This represents a particle system in Babylon.
  55022. * 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.
  55023. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55024. * @example https://doc.babylonjs.com/babylon101/particles
  55025. */
  55026. var ParticleSystem = /** @class */ (function () {
  55027. /**
  55028. * Instantiates a particle system.
  55029. * 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.
  55030. * @param name The name of the particle system
  55031. * @param capacity The max number of particles alive at the same time
  55032. * @param scene The scene the particle system belongs to
  55033. * @param customEffect a custom effect used to change the way particles are rendered by default
  55034. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55035. * @param epsilon Offset used to render the particles
  55036. */
  55037. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55038. if (customEffect === void 0) { customEffect = null; }
  55039. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55040. if (epsilon === void 0) { epsilon = 0.01; }
  55041. var _this = this;
  55042. /**
  55043. * List of animations used by the particle system.
  55044. */
  55045. this.animations = [];
  55046. /**
  55047. * The rendering group used by the Particle system to chose when to render.
  55048. */
  55049. this.renderingGroupId = 0;
  55050. /**
  55051. * The emitter represents the Mesh or position we are attaching the particle system to.
  55052. */
  55053. this.emitter = null;
  55054. /**
  55055. * The maximum number of particles to emit per frame
  55056. */
  55057. this.emitRate = 10;
  55058. /**
  55059. * If you want to launch only a few particles at once, that can be done, as well.
  55060. */
  55061. this.manualEmitCount = -1;
  55062. /**
  55063. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55064. */
  55065. this.updateSpeed = 0.01;
  55066. /**
  55067. * The amount of time the particle system is running (depends of the overall update speed).
  55068. */
  55069. this.targetStopDuration = 0;
  55070. /**
  55071. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55072. */
  55073. this.disposeOnStop = false;
  55074. /**
  55075. * Minimum power of emitting particles.
  55076. */
  55077. this.minEmitPower = 1;
  55078. /**
  55079. * Maximum power of emitting particles.
  55080. */
  55081. this.maxEmitPower = 1;
  55082. /**
  55083. * Minimum life time of emitting particles.
  55084. */
  55085. this.minLifeTime = 1;
  55086. /**
  55087. * Maximum life time of emitting particles.
  55088. */
  55089. this.maxLifeTime = 1;
  55090. /**
  55091. * Minimum Size of emitting particles.
  55092. */
  55093. this.minSize = 1;
  55094. /**
  55095. * Maximum Size of emitting particles.
  55096. */
  55097. this.maxSize = 1;
  55098. /**
  55099. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55100. */
  55101. this.minAngularSpeed = 0;
  55102. /**
  55103. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55104. */
  55105. this.maxAngularSpeed = 0;
  55106. /**
  55107. * The layer mask we are rendering the particles through.
  55108. */
  55109. this.layerMask = 0x0FFFFFFF;
  55110. /**
  55111. * This can help using your own shader to render the particle system.
  55112. * The according effect will be created
  55113. */
  55114. this.customShader = null;
  55115. /**
  55116. * By default particle system starts as soon as they are created. This prevents the
  55117. * automatic start to happen and let you decide when to start emitting particles.
  55118. */
  55119. this.preventAutoStart = false;
  55120. /**
  55121. * Callback triggered when the particle animation is ending.
  55122. */
  55123. this.onAnimationEnd = null;
  55124. /**
  55125. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55126. */
  55127. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55128. /**
  55129. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55130. * to override the particles.
  55131. */
  55132. this.forceDepthWrite = false;
  55133. /**
  55134. * You can use gravity if you want to give an orientation to your particles.
  55135. */
  55136. this.gravity = BABYLON.Vector3.Zero();
  55137. /**
  55138. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55139. */
  55140. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55141. /**
  55142. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55143. */
  55144. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55145. /**
  55146. * Color the particle will have at the end of its lifetime.
  55147. */
  55148. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55149. /**
  55150. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55151. */
  55152. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55153. /**
  55154. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55155. */
  55156. this.spriteCellLoop = true;
  55157. /**
  55158. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55159. */
  55160. this.spriteCellChangeSpeed = 0;
  55161. /**
  55162. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55163. */
  55164. this.startSpriteCellID = 0;
  55165. /**
  55166. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55167. */
  55168. this.endSpriteCellID = 0;
  55169. /**
  55170. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55171. */
  55172. this.spriteCellWidth = 0;
  55173. /**
  55174. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55175. */
  55176. this.spriteCellHeight = 0;
  55177. /**
  55178. * An event triggered when the system is disposed.
  55179. */
  55180. this.onDisposeObservable = new BABYLON.Observable();
  55181. this._particles = new Array();
  55182. this._stockParticles = new Array();
  55183. this._newPartsExcess = 0;
  55184. this._vertexBuffers = {};
  55185. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55186. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55187. this._scaledDirection = BABYLON.Vector3.Zero();
  55188. this._scaledGravity = BABYLON.Vector3.Zero();
  55189. this._currentRenderId = -1;
  55190. this._started = false;
  55191. this._stopped = false;
  55192. this._actualFrame = 0;
  55193. this._vertexBufferSize = 11;
  55194. // start of sub system methods
  55195. /**
  55196. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55197. * Its lifetime will start back at 0.
  55198. */
  55199. this.recycleParticle = function (particle) {
  55200. var lastParticle = _this._particles.pop();
  55201. if (lastParticle !== particle) {
  55202. lastParticle.copyTo(particle);
  55203. }
  55204. _this._stockParticles.push(lastParticle);
  55205. };
  55206. this._createParticle = function () {
  55207. var particle;
  55208. if (_this._stockParticles.length !== 0) {
  55209. particle = _this._stockParticles.pop();
  55210. particle.age = 0;
  55211. particle.cellIndex = _this.startSpriteCellID;
  55212. }
  55213. else {
  55214. particle = new BABYLON.Particle(_this);
  55215. }
  55216. return particle;
  55217. };
  55218. this._emitFromParticle = function (particle) {
  55219. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55220. return;
  55221. }
  55222. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55223. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55224. subSystem._rootParticleSystem = _this;
  55225. _this.activeSubSystems.push(subSystem);
  55226. subSystem.start();
  55227. };
  55228. this._appendParticleVertexes = null;
  55229. this.id = name;
  55230. this.name = name;
  55231. this._capacity = capacity;
  55232. this._epsilon = epsilon;
  55233. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55234. if (isAnimationSheetEnabled) {
  55235. this._vertexBufferSize = 12;
  55236. }
  55237. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55238. this._customEffect = customEffect;
  55239. scene.particleSystems.push(this);
  55240. this._createIndexBuffer();
  55241. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55242. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55243. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55244. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55245. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55246. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55247. if (this._isAnimationSheetEnabled) {
  55248. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55249. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55250. }
  55251. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55252. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55253. this._vertexBuffers["options"] = options;
  55254. // Default emitter type
  55255. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55256. this.updateFunction = function (particles) {
  55257. for (var index = 0; index < particles.length; index++) {
  55258. var particle = particles[index];
  55259. particle.age += _this._scaledUpdateSpeed;
  55260. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55261. _this._emitFromParticle(particle);
  55262. _this.recycleParticle(particle);
  55263. index--;
  55264. continue;
  55265. }
  55266. else {
  55267. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55268. particle.color.addInPlace(_this._scaledColorStep);
  55269. if (particle.color.a < 0)
  55270. particle.color.a = 0;
  55271. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55272. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55273. particle.position.addInPlace(_this._scaledDirection);
  55274. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55275. particle.direction.addInPlace(_this._scaledGravity);
  55276. if (_this._isAnimationSheetEnabled) {
  55277. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55278. }
  55279. }
  55280. }
  55281. };
  55282. }
  55283. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55284. /**
  55285. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55286. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55287. */
  55288. get: function () {
  55289. if (this.particleEmitterType.direction1) {
  55290. return this.particleEmitterType.direction1;
  55291. }
  55292. return BABYLON.Vector3.Zero();
  55293. },
  55294. set: function (value) {
  55295. if (this.particleEmitterType.direction1) {
  55296. this.particleEmitterType.direction1 = value;
  55297. }
  55298. },
  55299. enumerable: true,
  55300. configurable: true
  55301. });
  55302. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55303. /**
  55304. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55305. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55306. */
  55307. get: function () {
  55308. if (this.particleEmitterType.direction2) {
  55309. return this.particleEmitterType.direction2;
  55310. }
  55311. return BABYLON.Vector3.Zero();
  55312. },
  55313. set: function (value) {
  55314. if (this.particleEmitterType.direction2) {
  55315. this.particleEmitterType.direction2 = value;
  55316. }
  55317. },
  55318. enumerable: true,
  55319. configurable: true
  55320. });
  55321. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55322. /**
  55323. * 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.
  55324. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55325. */
  55326. get: function () {
  55327. if (this.particleEmitterType.minEmitBox) {
  55328. return this.particleEmitterType.minEmitBox;
  55329. }
  55330. return BABYLON.Vector3.Zero();
  55331. },
  55332. set: function (value) {
  55333. if (this.particleEmitterType.minEmitBox) {
  55334. this.particleEmitterType.minEmitBox = value;
  55335. }
  55336. },
  55337. enumerable: true,
  55338. configurable: true
  55339. });
  55340. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55341. /**
  55342. * 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.
  55343. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55344. */
  55345. get: function () {
  55346. if (this.particleEmitterType.maxEmitBox) {
  55347. return this.particleEmitterType.maxEmitBox;
  55348. }
  55349. return BABYLON.Vector3.Zero();
  55350. },
  55351. set: function (value) {
  55352. if (this.particleEmitterType.maxEmitBox) {
  55353. this.particleEmitterType.maxEmitBox = value;
  55354. }
  55355. },
  55356. enumerable: true,
  55357. configurable: true
  55358. });
  55359. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55360. /**
  55361. * Sets a callback that will be triggered when the system is disposed.
  55362. */
  55363. set: function (callback) {
  55364. if (this._onDisposeObserver) {
  55365. this.onDisposeObservable.remove(this._onDisposeObserver);
  55366. }
  55367. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55368. },
  55369. enumerable: true,
  55370. configurable: true
  55371. });
  55372. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55373. /**
  55374. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55375. */
  55376. get: function () {
  55377. return this._isAnimationSheetEnabled;
  55378. },
  55379. enumerable: true,
  55380. configurable: true
  55381. });
  55382. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55383. //end of Sub-emitter
  55384. /**
  55385. * Gets the current list of active particles
  55386. */
  55387. get: function () {
  55388. return this._particles;
  55389. },
  55390. enumerable: true,
  55391. configurable: true
  55392. });
  55393. /**
  55394. * Returns the string "ParticleSystem"
  55395. * @returns a string containing the class name
  55396. */
  55397. ParticleSystem.prototype.getClassName = function () {
  55398. return "ParticleSystem";
  55399. };
  55400. ParticleSystem.prototype._createIndexBuffer = function () {
  55401. var indices = [];
  55402. var index = 0;
  55403. for (var count = 0; count < this._capacity; count++) {
  55404. indices.push(index);
  55405. indices.push(index + 1);
  55406. indices.push(index + 2);
  55407. indices.push(index);
  55408. indices.push(index + 2);
  55409. indices.push(index + 3);
  55410. index += 4;
  55411. }
  55412. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55413. };
  55414. /**
  55415. * Gets the maximum number of particles active at the same time.
  55416. * @returns The max number of active particles.
  55417. */
  55418. ParticleSystem.prototype.getCapacity = function () {
  55419. return this._capacity;
  55420. };
  55421. /**
  55422. * Gets Wether there are still active particles in the system.
  55423. * @returns True if it is alive, otherwise false.
  55424. */
  55425. ParticleSystem.prototype.isAlive = function () {
  55426. return this._alive;
  55427. };
  55428. /**
  55429. * Gets Wether the system has been started.
  55430. * @returns True if it has been started, otherwise false.
  55431. */
  55432. ParticleSystem.prototype.isStarted = function () {
  55433. return this._started;
  55434. };
  55435. /**
  55436. * Starts the particle system and begins to emit.
  55437. */
  55438. ParticleSystem.prototype.start = function () {
  55439. this._started = true;
  55440. this._stopped = false;
  55441. this._actualFrame = 0;
  55442. if (this.subEmitters && this.subEmitters.length != 0) {
  55443. this.activeSubSystems = new Array();
  55444. }
  55445. };
  55446. /**
  55447. * Stops the particle system.
  55448. * @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.
  55449. */
  55450. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55451. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55452. this._stopped = true;
  55453. if (stopSubEmitters) {
  55454. this._stopSubEmitters();
  55455. }
  55456. };
  55457. // animation sheet
  55458. /**
  55459. * Remove all active particles
  55460. */
  55461. ParticleSystem.prototype.reset = function () {
  55462. this._stockParticles = [];
  55463. this._particles = [];
  55464. };
  55465. /**
  55466. * @ignore (for internal use only)
  55467. */
  55468. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55469. var offset = index * this._vertexBufferSize;
  55470. this._vertexData[offset] = particle.position.x;
  55471. this._vertexData[offset + 1] = particle.position.y;
  55472. this._vertexData[offset + 2] = particle.position.z;
  55473. this._vertexData[offset + 3] = particle.color.r;
  55474. this._vertexData[offset + 4] = particle.color.g;
  55475. this._vertexData[offset + 5] = particle.color.b;
  55476. this._vertexData[offset + 6] = particle.color.a;
  55477. this._vertexData[offset + 7] = particle.angle;
  55478. this._vertexData[offset + 8] = particle.size;
  55479. this._vertexData[offset + 9] = offsetX;
  55480. this._vertexData[offset + 10] = offsetY;
  55481. };
  55482. /**
  55483. * @ignore (for internal use only)
  55484. */
  55485. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55486. if (offsetX === 0)
  55487. offsetX = this._epsilon;
  55488. else if (offsetX === 1)
  55489. offsetX = 1 - this._epsilon;
  55490. if (offsetY === 0)
  55491. offsetY = this._epsilon;
  55492. else if (offsetY === 1)
  55493. offsetY = 1 - this._epsilon;
  55494. var offset = index * this._vertexBufferSize;
  55495. this._vertexData[offset] = particle.position.x;
  55496. this._vertexData[offset + 1] = particle.position.y;
  55497. this._vertexData[offset + 2] = particle.position.z;
  55498. this._vertexData[offset + 3] = particle.color.r;
  55499. this._vertexData[offset + 4] = particle.color.g;
  55500. this._vertexData[offset + 5] = particle.color.b;
  55501. this._vertexData[offset + 6] = particle.color.a;
  55502. this._vertexData[offset + 7] = particle.angle;
  55503. this._vertexData[offset + 8] = particle.size;
  55504. this._vertexData[offset + 9] = offsetX;
  55505. this._vertexData[offset + 10] = offsetY;
  55506. this._vertexData[offset + 11] = particle.cellIndex;
  55507. };
  55508. ParticleSystem.prototype._stopSubEmitters = function () {
  55509. if (!this.activeSubSystems) {
  55510. return;
  55511. }
  55512. this.activeSubSystems.forEach(function (subSystem) {
  55513. subSystem.stop(true);
  55514. });
  55515. this.activeSubSystems = new Array();
  55516. };
  55517. ParticleSystem.prototype._removeFromRoot = function () {
  55518. if (!this._rootParticleSystem) {
  55519. return;
  55520. }
  55521. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55522. if (index !== -1) {
  55523. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55524. }
  55525. };
  55526. // end of sub system methods
  55527. ParticleSystem.prototype._update = function (newParticles) {
  55528. // Update current
  55529. this._alive = this._particles.length > 0;
  55530. this.updateFunction(this._particles);
  55531. // Add new ones
  55532. var worldMatrix;
  55533. if (this.emitter.position) {
  55534. var emitterMesh = this.emitter;
  55535. worldMatrix = emitterMesh.getWorldMatrix();
  55536. }
  55537. else {
  55538. var emitterPosition = this.emitter;
  55539. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55540. }
  55541. var particle;
  55542. for (var index = 0; index < newParticles; index++) {
  55543. if (this._particles.length === this._capacity) {
  55544. break;
  55545. }
  55546. particle = this._createParticle();
  55547. this._particles.push(particle);
  55548. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55549. if (this.startPositionFunction) {
  55550. this.startPositionFunction(worldMatrix, particle.position, particle);
  55551. }
  55552. else {
  55553. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55554. }
  55555. if (this.startDirectionFunction) {
  55556. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55557. }
  55558. else {
  55559. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55560. }
  55561. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55562. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55563. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55564. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55565. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55566. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55567. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55568. }
  55569. };
  55570. ParticleSystem.prototype._getEffect = function () {
  55571. if (this._customEffect) {
  55572. return this._customEffect;
  55573. }
  55574. ;
  55575. var defines = [];
  55576. if (this._scene.clipPlane) {
  55577. defines.push("#define CLIPPLANE");
  55578. }
  55579. if (this._isAnimationSheetEnabled) {
  55580. defines.push("#define ANIMATESHEET");
  55581. }
  55582. // Effect
  55583. var join = defines.join("\n");
  55584. if (this._cachedDefines !== join) {
  55585. this._cachedDefines = join;
  55586. var attributesNamesOrOptions;
  55587. var effectCreationOption;
  55588. if (this._isAnimationSheetEnabled) {
  55589. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55590. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55591. }
  55592. else {
  55593. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55594. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55595. }
  55596. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55597. }
  55598. return this._effect;
  55599. };
  55600. /**
  55601. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55602. */
  55603. ParticleSystem.prototype.animate = function () {
  55604. if (!this._started)
  55605. return;
  55606. var effect = this._getEffect();
  55607. // Check
  55608. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55609. return;
  55610. if (this._currentRenderId === this._scene.getRenderId()) {
  55611. return;
  55612. }
  55613. this._currentRenderId = this._scene.getRenderId();
  55614. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55615. // determine the number of particles we need to create
  55616. var newParticles;
  55617. if (this.manualEmitCount > -1) {
  55618. newParticles = this.manualEmitCount;
  55619. this._newPartsExcess = 0;
  55620. this.manualEmitCount = 0;
  55621. }
  55622. else {
  55623. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55624. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55625. }
  55626. if (this._newPartsExcess > 1.0) {
  55627. newParticles += this._newPartsExcess >> 0;
  55628. this._newPartsExcess -= this._newPartsExcess >> 0;
  55629. }
  55630. this._alive = false;
  55631. if (!this._stopped) {
  55632. this._actualFrame += this._scaledUpdateSpeed;
  55633. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55634. this.stop();
  55635. }
  55636. else {
  55637. newParticles = 0;
  55638. }
  55639. this._update(newParticles);
  55640. // Stopped?
  55641. if (this._stopped) {
  55642. if (!this._alive) {
  55643. this._started = false;
  55644. if (this.onAnimationEnd) {
  55645. this.onAnimationEnd();
  55646. }
  55647. if (this.disposeOnStop) {
  55648. this._scene._toBeDisposed.push(this);
  55649. }
  55650. }
  55651. }
  55652. // Animation sheet
  55653. if (this._isAnimationSheetEnabled) {
  55654. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55655. }
  55656. else {
  55657. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55658. }
  55659. // Update VBO
  55660. var offset = 0;
  55661. for (var index = 0; index < this._particles.length; index++) {
  55662. var particle = this._particles[index];
  55663. this._appendParticleVertexes(offset, particle);
  55664. offset += 4;
  55665. }
  55666. if (this._vertexBuffer) {
  55667. this._vertexBuffer.update(this._vertexData);
  55668. }
  55669. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55670. this.stop();
  55671. }
  55672. };
  55673. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55674. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55675. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55676. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55677. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55678. };
  55679. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55680. this._appendParticleVertex(offset++, particle, 0, 0);
  55681. this._appendParticleVertex(offset++, particle, 1, 0);
  55682. this._appendParticleVertex(offset++, particle, 1, 1);
  55683. this._appendParticleVertex(offset++, particle, 0, 1);
  55684. };
  55685. /**
  55686. * Rebuilds the particle system.
  55687. */
  55688. ParticleSystem.prototype.rebuild = function () {
  55689. this._createIndexBuffer();
  55690. if (this._vertexBuffer) {
  55691. this._vertexBuffer._rebuild();
  55692. }
  55693. };
  55694. /**
  55695. * Is this system ready to be used/rendered
  55696. * @return true if the system is ready
  55697. */
  55698. ParticleSystem.prototype.isReady = function () {
  55699. var effect = this._getEffect();
  55700. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55701. return false;
  55702. }
  55703. return true;
  55704. };
  55705. /**
  55706. * Renders the particle system in its current state.
  55707. * @returns the current number of particles
  55708. */
  55709. ParticleSystem.prototype.render = function () {
  55710. var effect = this._getEffect();
  55711. // Check
  55712. if (!this.isReady() || !this._particles.length) {
  55713. return 0;
  55714. }
  55715. var engine = this._scene.getEngine();
  55716. // Render
  55717. engine.enableEffect(effect);
  55718. engine.setState(false);
  55719. var viewMatrix = this._scene.getViewMatrix();
  55720. effect.setTexture("diffuseSampler", this.particleTexture);
  55721. effect.setMatrix("view", viewMatrix);
  55722. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55723. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55724. var baseSize = this.particleTexture.getBaseSize();
  55725. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55726. }
  55727. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55728. if (this._scene.clipPlane) {
  55729. var clipPlane = this._scene.clipPlane;
  55730. var invView = viewMatrix.clone();
  55731. invView.invert();
  55732. effect.setMatrix("invView", invView);
  55733. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55734. }
  55735. // VBOs
  55736. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55737. // Draw order
  55738. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55739. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55740. }
  55741. else {
  55742. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55743. }
  55744. if (this.forceDepthWrite) {
  55745. engine.setDepthWrite(true);
  55746. }
  55747. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55749. return this._particles.length;
  55750. };
  55751. /**
  55752. * Disposes the particle system and free the associated resources
  55753. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55754. */
  55755. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55756. if (disposeTexture === void 0) { disposeTexture = true; }
  55757. if (this._vertexBuffer) {
  55758. this._vertexBuffer.dispose();
  55759. this._vertexBuffer = null;
  55760. }
  55761. if (this._indexBuffer) {
  55762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55763. this._indexBuffer = null;
  55764. }
  55765. if (disposeTexture && this.particleTexture) {
  55766. this.particleTexture.dispose();
  55767. this.particleTexture = null;
  55768. }
  55769. this._removeFromRoot();
  55770. // Remove from scene
  55771. var index = this._scene.particleSystems.indexOf(this);
  55772. if (index > -1) {
  55773. this._scene.particleSystems.splice(index, 1);
  55774. }
  55775. // Callback
  55776. this.onDisposeObservable.notifyObservers(this);
  55777. this.onDisposeObservable.clear();
  55778. };
  55779. /**
  55780. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55781. * @param radius The radius of the sphere to emit from
  55782. * @returns the emitter
  55783. */
  55784. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55785. if (radius === void 0) { radius = 1; }
  55786. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55787. this.particleEmitterType = particleEmitter;
  55788. return particleEmitter;
  55789. };
  55790. /**
  55791. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55792. * @param radius The radius of the sphere to emit from
  55793. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55794. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55795. * @returns the emitter
  55796. */
  55797. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55798. if (radius === void 0) { radius = 1; }
  55799. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55800. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55801. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55802. this.particleEmitterType = particleEmitter;
  55803. return particleEmitter;
  55804. };
  55805. /**
  55806. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55807. * @param radius The radius of the cone to emit from
  55808. * @param angle The base angle of the cone
  55809. * @returns the emitter
  55810. */
  55811. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55812. if (radius === void 0) { radius = 1; }
  55813. if (angle === void 0) { angle = Math.PI / 4; }
  55814. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55815. this.particleEmitterType = particleEmitter;
  55816. return particleEmitter;
  55817. };
  55818. // 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.
  55819. /**
  55820. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55821. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55822. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55823. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55824. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55825. * @returns the emitter
  55826. */
  55827. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55828. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55829. this.particleEmitterType = particleEmitter;
  55830. this.direction1 = direction1;
  55831. this.direction2 = direction2;
  55832. this.minEmitBox = minEmitBox;
  55833. this.maxEmitBox = maxEmitBox;
  55834. return particleEmitter;
  55835. };
  55836. // Clone
  55837. /**
  55838. * Clones the particle system.
  55839. * @param name The name of the cloned object
  55840. * @param newEmitter The new emitter to use
  55841. * @returns the cloned particle system
  55842. */
  55843. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55844. var custom = null;
  55845. var program = null;
  55846. if (this.customShader != null) {
  55847. program = this.customShader;
  55848. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55849. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55850. }
  55851. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55852. result.customShader = program;
  55853. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55854. if (newEmitter === undefined) {
  55855. newEmitter = this.emitter;
  55856. }
  55857. result.emitter = newEmitter;
  55858. if (this.particleTexture) {
  55859. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55860. }
  55861. if (!this.preventAutoStart) {
  55862. result.start();
  55863. }
  55864. return result;
  55865. };
  55866. /**
  55867. * Serializes the particle system to a JSON object.
  55868. * @returns the JSON object
  55869. */
  55870. ParticleSystem.prototype.serialize = function () {
  55871. var serializationObject = {};
  55872. serializationObject.name = this.name;
  55873. serializationObject.id = this.id;
  55874. // Emitter
  55875. if (this.emitter.position) {
  55876. var emitterMesh = this.emitter;
  55877. serializationObject.emitterId = emitterMesh.id;
  55878. }
  55879. else {
  55880. var emitterPosition = this.emitter;
  55881. serializationObject.emitter = emitterPosition.asArray();
  55882. }
  55883. serializationObject.capacity = this.getCapacity();
  55884. if (this.particleTexture) {
  55885. serializationObject.textureName = this.particleTexture.name;
  55886. }
  55887. // Animations
  55888. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55889. // Particle system
  55890. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55891. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55892. serializationObject.minSize = this.minSize;
  55893. serializationObject.maxSize = this.maxSize;
  55894. serializationObject.minEmitPower = this.minEmitPower;
  55895. serializationObject.maxEmitPower = this.maxEmitPower;
  55896. serializationObject.minLifeTime = this.minLifeTime;
  55897. serializationObject.maxLifeTime = this.maxLifeTime;
  55898. serializationObject.emitRate = this.emitRate;
  55899. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55900. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55901. serializationObject.gravity = this.gravity.asArray();
  55902. serializationObject.direction1 = this.direction1.asArray();
  55903. serializationObject.direction2 = this.direction2.asArray();
  55904. serializationObject.color1 = this.color1.asArray();
  55905. serializationObject.color2 = this.color2.asArray();
  55906. serializationObject.colorDead = this.colorDead.asArray();
  55907. serializationObject.updateSpeed = this.updateSpeed;
  55908. serializationObject.targetStopDuration = this.targetStopDuration;
  55909. serializationObject.textureMask = this.textureMask.asArray();
  55910. serializationObject.blendMode = this.blendMode;
  55911. serializationObject.customShader = this.customShader;
  55912. serializationObject.preventAutoStart = this.preventAutoStart;
  55913. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55914. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55915. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55916. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55917. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55918. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55919. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55920. // Emitter
  55921. if (this.particleEmitterType) {
  55922. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55923. }
  55924. return serializationObject;
  55925. };
  55926. /**
  55927. * Parses a JSON object to create a particle system.
  55928. * @param parsedParticleSystem The JSON object to parse
  55929. * @param scene The scene to create the particle system in
  55930. * @param rootUrl The root url to use to load external dependencies like texture
  55931. * @returns the Parsed particle system
  55932. */
  55933. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55934. var name = parsedParticleSystem.name;
  55935. var custom = null;
  55936. var program = null;
  55937. if (parsedParticleSystem.customShader) {
  55938. program = parsedParticleSystem.customShader;
  55939. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55940. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55941. }
  55942. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55943. particleSystem.customShader = program;
  55944. if (parsedParticleSystem.id) {
  55945. particleSystem.id = parsedParticleSystem.id;
  55946. }
  55947. // Auto start
  55948. if (parsedParticleSystem.preventAutoStart) {
  55949. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55950. }
  55951. // Texture
  55952. if (parsedParticleSystem.textureName) {
  55953. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55954. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55955. }
  55956. // Emitter
  55957. if (parsedParticleSystem.emitterId) {
  55958. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55959. }
  55960. else {
  55961. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55962. }
  55963. // Animations
  55964. if (parsedParticleSystem.animations) {
  55965. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55966. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55967. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55968. }
  55969. }
  55970. if (parsedParticleSystem.autoAnimate) {
  55971. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55972. }
  55973. // Particle system
  55974. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55975. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55976. particleSystem.minSize = parsedParticleSystem.minSize;
  55977. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55978. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55979. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55980. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55981. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55982. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55983. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55984. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55985. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55986. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55987. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55988. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55989. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55990. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55991. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55992. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55993. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55994. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55995. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55996. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55997. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55998. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55999. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56000. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56001. if (!particleSystem.preventAutoStart) {
  56002. particleSystem.start();
  56003. }
  56004. return particleSystem;
  56005. };
  56006. /**
  56007. * Source color is added to the destination color without alpha affecting the result.
  56008. */
  56009. ParticleSystem.BLENDMODE_ONEONE = 0;
  56010. /**
  56011. * Blend current color and particle color using particle’s alpha.
  56012. */
  56013. ParticleSystem.BLENDMODE_STANDARD = 1;
  56014. return ParticleSystem;
  56015. }());
  56016. BABYLON.ParticleSystem = ParticleSystem;
  56017. })(BABYLON || (BABYLON = {}));
  56018. //# sourceMappingURL=babylon.particleSystem.js.map
  56019. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56020. var BABYLON;
  56021. (function (BABYLON) {
  56022. /**
  56023. * Particle emitter emitting particles from the inside of a box.
  56024. * It emits the particles randomly between 2 given directions.
  56025. */
  56026. var BoxParticleEmitter = /** @class */ (function () {
  56027. /**
  56028. * Creates a new instance BoxParticleEmitter
  56029. */
  56030. function BoxParticleEmitter() {
  56031. /**
  56032. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56033. */
  56034. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56035. /**
  56036. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56037. */
  56038. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56039. /**
  56040. * 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.
  56041. */
  56042. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56043. /**
  56044. * 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.
  56045. */
  56046. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56047. }
  56048. /**
  56049. * Called by the particle System when the direction is computed for the created particle.
  56050. * @param emitPower is the power of the particle (speed)
  56051. * @param worldMatrix is the world matrix of the particle system
  56052. * @param directionToUpdate is the direction vector to update with the result
  56053. * @param particle is the particle we are computed the direction for
  56054. */
  56055. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56056. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56057. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56058. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56059. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56060. };
  56061. /**
  56062. * Called by the particle System when the position is computed for the created particle.
  56063. * @param worldMatrix is the world matrix of the particle system
  56064. * @param positionToUpdate is the position vector to update with the result
  56065. * @param particle is the particle we are computed the position for
  56066. */
  56067. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56068. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56069. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56070. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56071. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56072. };
  56073. /**
  56074. * Clones the current emitter and returns a copy of it
  56075. * @returns the new emitter
  56076. */
  56077. BoxParticleEmitter.prototype.clone = function () {
  56078. var newOne = new BoxParticleEmitter();
  56079. BABYLON.Tools.DeepCopy(this, newOne);
  56080. return newOne;
  56081. };
  56082. /**
  56083. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56084. * @param effect defines the update shader
  56085. */
  56086. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56087. effect.setVector3("direction1", this.direction1);
  56088. effect.setVector3("direction2", this.direction2);
  56089. effect.setVector3("minEmitBox", this.minEmitBox);
  56090. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56091. };
  56092. /**
  56093. * Returns a string to use to update the GPU particles update shader
  56094. * @returns a string containng the defines string
  56095. */
  56096. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56097. return "#define BOXEMITTER";
  56098. };
  56099. /**
  56100. * Returns the string "BoxEmitter"
  56101. * @returns a string containing the class name
  56102. */
  56103. BoxParticleEmitter.prototype.getClassName = function () {
  56104. return "BoxEmitter";
  56105. };
  56106. /**
  56107. * Serializes the particle system to a JSON object.
  56108. * @returns the JSON object
  56109. */
  56110. BoxParticleEmitter.prototype.serialize = function () {
  56111. var serializationObject = {};
  56112. serializationObject.type = this.getClassName();
  56113. serializationObject.direction1 = this.direction1.asArray();
  56114. ;
  56115. serializationObject.direction2 = this.direction2.asArray();
  56116. ;
  56117. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56118. ;
  56119. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56120. ;
  56121. return serializationObject;
  56122. };
  56123. /**
  56124. * Parse properties from a JSON object
  56125. * @param serializationObject defines the JSON object
  56126. */
  56127. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56128. this.direction1.copyFrom(serializationObject.direction1);
  56129. this.direction2.copyFrom(serializationObject.direction2);
  56130. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56131. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56132. };
  56133. return BoxParticleEmitter;
  56134. }());
  56135. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56136. })(BABYLON || (BABYLON = {}));
  56137. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56138. var BABYLON;
  56139. (function (BABYLON) {
  56140. /**
  56141. * Particle emitter emitting particles from the inside of a cone.
  56142. * It emits the particles alongside the cone volume from the base to the particle.
  56143. * The emission direction might be randomized.
  56144. */
  56145. var ConeParticleEmitter = /** @class */ (function () {
  56146. /**
  56147. * Creates a new instance ConeParticleEmitter
  56148. * @param radius the radius of the emission cone (1 by default)
  56149. * @param angles the cone base angle (PI by default)
  56150. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56151. */
  56152. function ConeParticleEmitter(radius,
  56153. /**
  56154. * The radius of the emission cone.
  56155. */
  56156. angle,
  56157. /**
  56158. * The cone base angle.
  56159. */
  56160. directionRandomizer) {
  56161. if (radius === void 0) { radius = 1; }
  56162. if (angle === void 0) { angle = Math.PI; }
  56163. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56164. this.angle = angle;
  56165. this.directionRandomizer = directionRandomizer;
  56166. this.radius = radius;
  56167. }
  56168. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56169. /**
  56170. * Gets the radius of the emission cone.
  56171. */
  56172. get: function () {
  56173. return this._radius;
  56174. },
  56175. /**
  56176. * Sets the radius of the emission cone.
  56177. */
  56178. set: function (value) {
  56179. this._radius = value;
  56180. if (this.angle !== 0) {
  56181. this._height = value / Math.tan(this.angle / 2);
  56182. }
  56183. else {
  56184. this._height = 1;
  56185. }
  56186. },
  56187. enumerable: true,
  56188. configurable: true
  56189. });
  56190. /**
  56191. * Called by the particle System when the direction is computed for the created particle.
  56192. * @param emitPower is the power of the particle (speed)
  56193. * @param worldMatrix is the world matrix of the particle system
  56194. * @param directionToUpdate is the direction vector to update with the result
  56195. * @param particle is the particle we are computed the direction for
  56196. */
  56197. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56198. if (this.angle === 0) {
  56199. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56200. }
  56201. else {
  56202. // measure the direction Vector from the emitter to the particle.
  56203. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56204. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56205. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56206. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56207. direction.x += randX;
  56208. direction.y += randY;
  56209. direction.z += randZ;
  56210. direction.normalize();
  56211. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56212. }
  56213. };
  56214. /**
  56215. * Called by the particle System when the position is computed for the created particle.
  56216. * @param worldMatrix is the world matrix of the particle system
  56217. * @param positionToUpdate is the position vector to update with the result
  56218. * @param particle is the particle we are computed the position for
  56219. */
  56220. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56221. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56222. var h = BABYLON.Scalar.RandomRange(0, 1);
  56223. // Better distribution in a cone at normal angles.
  56224. h = 1 - h * h;
  56225. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56226. radius = radius * h;
  56227. var randX = radius * Math.sin(s);
  56228. var randZ = radius * Math.cos(s);
  56229. var randY = h * this._height;
  56230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56231. };
  56232. /**
  56233. * Clones the current emitter and returns a copy of it
  56234. * @returns the new emitter
  56235. */
  56236. ConeParticleEmitter.prototype.clone = function () {
  56237. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56238. BABYLON.Tools.DeepCopy(this, newOne);
  56239. return newOne;
  56240. };
  56241. /**
  56242. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56243. * @param effect defines the update shader
  56244. */
  56245. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56246. effect.setFloat("radius", this.radius);
  56247. effect.setFloat("angle", this.angle);
  56248. effect.setFloat("height", this._height);
  56249. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56250. };
  56251. /**
  56252. * Returns a string to use to update the GPU particles update shader
  56253. * @returns a string containng the defines string
  56254. */
  56255. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56256. return "#define CONEEMITTER";
  56257. };
  56258. /**
  56259. * Returns the string "BoxEmitter"
  56260. * @returns a string containing the class name
  56261. */
  56262. ConeParticleEmitter.prototype.getClassName = function () {
  56263. return "ConeEmitter";
  56264. };
  56265. /**
  56266. * Serializes the particle system to a JSON object.
  56267. * @returns the JSON object
  56268. */
  56269. ConeParticleEmitter.prototype.serialize = function () {
  56270. var serializationObject = {};
  56271. serializationObject.type = this.getClassName();
  56272. serializationObject.radius = this.radius;
  56273. serializationObject.angle = this.angle;
  56274. serializationObject.directionRandomizer = this.directionRandomizer;
  56275. return serializationObject;
  56276. };
  56277. /**
  56278. * Parse properties from a JSON object
  56279. * @param serializationObject defines the JSON object
  56280. */
  56281. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56282. this.radius = serializationObject.radius;
  56283. this.angle = serializationObject.angle;
  56284. this.directionRandomizer = serializationObject.directionRandomizer;
  56285. };
  56286. return ConeParticleEmitter;
  56287. }());
  56288. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56289. })(BABYLON || (BABYLON = {}));
  56290. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56291. var BABYLON;
  56292. (function (BABYLON) {
  56293. /**
  56294. * Particle emitter emitting particles from the inside of a sphere.
  56295. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56296. */
  56297. var SphereParticleEmitter = /** @class */ (function () {
  56298. /**
  56299. * Creates a new instance SphereParticleEmitter
  56300. * @param radius the radius of the emission sphere (1 by default)
  56301. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56302. */
  56303. function SphereParticleEmitter(
  56304. /**
  56305. * The radius of the emission sphere.
  56306. */
  56307. radius,
  56308. /**
  56309. * How much to randomize the particle direction [0-1].
  56310. */
  56311. directionRandomizer) {
  56312. if (radius === void 0) { radius = 1; }
  56313. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56314. this.radius = radius;
  56315. this.directionRandomizer = directionRandomizer;
  56316. }
  56317. /**
  56318. * Called by the particle System when the direction is computed for the created particle.
  56319. * @param emitPower is the power of the particle (speed)
  56320. * @param worldMatrix is the world matrix of the particle system
  56321. * @param directionToUpdate is the direction vector to update with the result
  56322. * @param particle is the particle we are computed the direction for
  56323. */
  56324. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56325. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56326. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56327. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56328. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56329. direction.x += randX;
  56330. direction.y += randY;
  56331. direction.z += randZ;
  56332. direction.normalize();
  56333. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56334. };
  56335. /**
  56336. * Called by the particle System when the position is computed for the created particle.
  56337. * @param worldMatrix is the world matrix of the particle system
  56338. * @param positionToUpdate is the position vector to update with the result
  56339. * @param particle is the particle we are computed the position for
  56340. */
  56341. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56342. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56343. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56344. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56345. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56346. var randY = randRadius * Math.cos(theta);
  56347. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56348. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56349. };
  56350. /**
  56351. * Clones the current emitter and returns a copy of it
  56352. * @returns the new emitter
  56353. */
  56354. SphereParticleEmitter.prototype.clone = function () {
  56355. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56356. BABYLON.Tools.DeepCopy(this, newOne);
  56357. return newOne;
  56358. };
  56359. /**
  56360. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56361. * @param effect defines the update shader
  56362. */
  56363. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56364. effect.setFloat("radius", this.radius);
  56365. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56366. };
  56367. /**
  56368. * Returns a string to use to update the GPU particles update shader
  56369. * @returns a string containng the defines string
  56370. */
  56371. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56372. return "#define SPHEREEMITTER";
  56373. };
  56374. /**
  56375. * Returns the string "SphereParticleEmitter"
  56376. * @returns a string containing the class name
  56377. */
  56378. SphereParticleEmitter.prototype.getClassName = function () {
  56379. return "SphereParticleEmitter";
  56380. };
  56381. /**
  56382. * Serializes the particle system to a JSON object.
  56383. * @returns the JSON object
  56384. */
  56385. SphereParticleEmitter.prototype.serialize = function () {
  56386. var serializationObject = {};
  56387. serializationObject.type = this.getClassName();
  56388. serializationObject.radius = this.radius;
  56389. serializationObject.directionRandomizer = this.directionRandomizer;
  56390. return serializationObject;
  56391. };
  56392. /**
  56393. * Parse properties from a JSON object
  56394. * @param serializationObject defines the JSON object
  56395. */
  56396. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56397. this.radius = serializationObject.radius;
  56398. this.directionRandomizer = serializationObject.directionRandomizer;
  56399. };
  56400. return SphereParticleEmitter;
  56401. }());
  56402. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56403. /**
  56404. * Particle emitter emitting particles from the inside of a sphere.
  56405. * It emits the particles randomly between two vectors.
  56406. */
  56407. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56408. __extends(SphereDirectedParticleEmitter, _super);
  56409. /**
  56410. * Creates a new instance SphereDirectedParticleEmitter
  56411. * @param radius the radius of the emission sphere (1 by default)
  56412. * @param direction1 the min limit of the emission direction (up vector by default)
  56413. * @param direction2 the max limit of the emission direction (up vector by default)
  56414. */
  56415. function SphereDirectedParticleEmitter(radius,
  56416. /**
  56417. * The min limit of the emission direction.
  56418. */
  56419. direction1,
  56420. /**
  56421. * The max limit of the emission direction.
  56422. */
  56423. direction2) {
  56424. if (radius === void 0) { radius = 1; }
  56425. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56426. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56427. var _this = _super.call(this, radius) || this;
  56428. _this.direction1 = direction1;
  56429. _this.direction2 = direction2;
  56430. return _this;
  56431. }
  56432. /**
  56433. * Called by the particle System when the direction is computed for the created particle.
  56434. * @param emitPower is the power of the particle (speed)
  56435. * @param worldMatrix is the world matrix of the particle system
  56436. * @param directionToUpdate is the direction vector to update with the result
  56437. * @param particle is the particle we are computed the direction for
  56438. */
  56439. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56440. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56441. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56442. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56443. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56444. };
  56445. /**
  56446. * Clones the current emitter and returns a copy of it
  56447. * @returns the new emitter
  56448. */
  56449. SphereDirectedParticleEmitter.prototype.clone = function () {
  56450. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56451. BABYLON.Tools.DeepCopy(this, newOne);
  56452. return newOne;
  56453. };
  56454. /**
  56455. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56456. * @param effect defines the update shader
  56457. */
  56458. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56459. effect.setFloat("radius", this.radius);
  56460. effect.setVector3("direction1", this.direction1);
  56461. effect.setVector3("direction2", this.direction2);
  56462. };
  56463. /**
  56464. * Returns a string to use to update the GPU particles update shader
  56465. * @returns a string containng the defines string
  56466. */
  56467. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56468. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56469. };
  56470. /**
  56471. * Returns the string "SphereDirectedParticleEmitter"
  56472. * @returns a string containing the class name
  56473. */
  56474. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56475. return "SphereDirectedParticleEmitter";
  56476. };
  56477. /**
  56478. * Serializes the particle system to a JSON object.
  56479. * @returns the JSON object
  56480. */
  56481. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56482. var serializationObject = _super.prototype.serialize.call(this);
  56483. ;
  56484. serializationObject.direction1 = this.direction1.asArray();
  56485. ;
  56486. serializationObject.direction2 = this.direction2.asArray();
  56487. ;
  56488. return serializationObject;
  56489. };
  56490. /**
  56491. * Parse properties from a JSON object
  56492. * @param serializationObject defines the JSON object
  56493. */
  56494. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56495. _super.prototype.parse.call(this, serializationObject);
  56496. this.direction1.copyFrom(serializationObject.direction1);
  56497. this.direction2.copyFrom(serializationObject.direction2);
  56498. };
  56499. return SphereDirectedParticleEmitter;
  56500. }(SphereParticleEmitter));
  56501. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56502. })(BABYLON || (BABYLON = {}));
  56503. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56504. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56505. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56506. s = arguments[i];
  56507. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56508. t[p] = s[p];
  56509. }
  56510. return t;
  56511. };
  56512. var BABYLON;
  56513. (function (BABYLON) {
  56514. /**
  56515. * This represents a GPU particle system in Babylon
  56516. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56517. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56518. */
  56519. var GPUParticleSystem = /** @class */ (function () {
  56520. /**
  56521. * Instantiates a GPU particle system.
  56522. * 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.
  56523. * @param name The name of the particle system
  56524. * @param capacity The max number of particles alive at the same time
  56525. * @param scene The scene the particle system belongs to
  56526. */
  56527. function GPUParticleSystem(name, options, scene) {
  56528. /**
  56529. * The emitter represents the Mesh or position we are attaching the particle system to.
  56530. */
  56531. this.emitter = null;
  56532. /**
  56533. * The rendering group used by the Particle system to chose when to render.
  56534. */
  56535. this.renderingGroupId = 0;
  56536. /**
  56537. * The layer mask we are rendering the particles through.
  56538. */
  56539. this.layerMask = 0x0FFFFFFF;
  56540. this._targetIndex = 0;
  56541. this._currentRenderId = -1;
  56542. this._started = false;
  56543. this._stopped = false;
  56544. this._timeDelta = 0;
  56545. this._attributesStrideSize = 14;
  56546. this._actualFrame = 0;
  56547. /**
  56548. * List of animations used by the particle system.
  56549. */
  56550. this.animations = [];
  56551. /**
  56552. * An event triggered when the system is disposed.
  56553. */
  56554. this.onDisposeObservable = new BABYLON.Observable();
  56555. /**
  56556. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56557. */
  56558. this.updateSpeed = 0.01;
  56559. /**
  56560. * The amount of time the particle system is running (depends of the overall update speed).
  56561. */
  56562. this.targetStopDuration = 0;
  56563. /**
  56564. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56565. */
  56566. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56567. /**
  56568. * Minimum life time of emitting particles.
  56569. */
  56570. this.minLifeTime = 1;
  56571. /**
  56572. * Maximum life time of emitting particles.
  56573. */
  56574. this.maxLifeTime = 1;
  56575. /**
  56576. * Minimum Size of emitting particles.
  56577. */
  56578. this.minSize = 1;
  56579. /**
  56580. * Maximum Size of emitting particles.
  56581. */
  56582. this.maxSize = 1;
  56583. /**
  56584. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56585. */
  56586. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56587. /**
  56588. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56589. */
  56590. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56591. /**
  56592. * Color the particle will have at the end of its lifetime.
  56593. */
  56594. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56595. /**
  56596. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56597. */
  56598. this.emitRate = 100;
  56599. /**
  56600. * You can use gravity if you want to give an orientation to your particles.
  56601. */
  56602. this.gravity = BABYLON.Vector3.Zero();
  56603. /**
  56604. * Minimum power of emitting particles.
  56605. */
  56606. this.minEmitPower = 1;
  56607. /**
  56608. * Maximum power of emitting particles.
  56609. */
  56610. this.maxEmitPower = 1;
  56611. /**
  56612. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56613. * to override the particles.
  56614. */
  56615. this.forceDepthWrite = false;
  56616. this.id = name;
  56617. this.name = name;
  56618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56619. this._engine = this._scene.getEngine();
  56620. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56621. this._capacity = fullOptions.capacity;
  56622. this._activeCount = fullOptions.capacity;
  56623. this._currentActiveCount = 0;
  56624. this._scene.particleSystems.push(this);
  56625. this._updateEffectOptions = {
  56626. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56627. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56628. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56629. uniformBuffersNames: [],
  56630. samplers: ["randomSampler"],
  56631. defines: "",
  56632. fallbacks: null,
  56633. onCompiled: null,
  56634. onError: null,
  56635. indexParameters: null,
  56636. maxSimultaneousLights: 0,
  56637. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56638. };
  56639. // Random data
  56640. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56641. var d = [];
  56642. for (var i = 0; i < maxTextureSize; ++i) {
  56643. d.push(Math.random());
  56644. d.push(Math.random());
  56645. d.push(Math.random());
  56646. d.push(Math.random());
  56647. }
  56648. 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);
  56649. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56650. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56651. this._randomTextureSize = maxTextureSize;
  56652. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56653. }
  56654. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56655. /**
  56656. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56657. */
  56658. get: function () {
  56659. if (!BABYLON.Engine.LastCreatedEngine) {
  56660. return false;
  56661. }
  56662. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56663. },
  56664. enumerable: true,
  56665. configurable: true
  56666. });
  56667. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56668. /**
  56669. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56670. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56671. */
  56672. get: function () {
  56673. if (this.particleEmitterType.direction1) {
  56674. return this.particleEmitterType.direction1;
  56675. }
  56676. return BABYLON.Vector3.Zero();
  56677. },
  56678. set: function (value) {
  56679. if (this.particleEmitterType.direction1) {
  56680. this.particleEmitterType.direction1 = value;
  56681. }
  56682. },
  56683. enumerable: true,
  56684. configurable: true
  56685. });
  56686. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56687. /**
  56688. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56689. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56690. */
  56691. get: function () {
  56692. if (this.particleEmitterType.direction2) {
  56693. return this.particleEmitterType.direction2;
  56694. }
  56695. return BABYLON.Vector3.Zero();
  56696. },
  56697. set: function (value) {
  56698. if (this.particleEmitterType.direction2) {
  56699. this.particleEmitterType.direction2 = value;
  56700. }
  56701. },
  56702. enumerable: true,
  56703. configurable: true
  56704. });
  56705. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56706. /**
  56707. * 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.
  56708. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56709. */
  56710. get: function () {
  56711. if (this.particleEmitterType.minEmitBox) {
  56712. return this.particleEmitterType.minEmitBox;
  56713. }
  56714. return BABYLON.Vector3.Zero();
  56715. },
  56716. set: function (value) {
  56717. if (this.particleEmitterType.minEmitBox) {
  56718. this.particleEmitterType.minEmitBox = value;
  56719. }
  56720. },
  56721. enumerable: true,
  56722. configurable: true
  56723. });
  56724. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56725. /**
  56726. * 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.
  56727. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56728. */
  56729. get: function () {
  56730. if (this.particleEmitterType.maxEmitBox) {
  56731. return this.particleEmitterType.maxEmitBox;
  56732. }
  56733. return BABYLON.Vector3.Zero();
  56734. },
  56735. set: function (value) {
  56736. if (this.particleEmitterType.maxEmitBox) {
  56737. this.particleEmitterType.maxEmitBox = value;
  56738. }
  56739. },
  56740. enumerable: true,
  56741. configurable: true
  56742. });
  56743. /**
  56744. * Gets the maximum number of particles active at the same time.
  56745. * @returns The max number of active particles.
  56746. */
  56747. GPUParticleSystem.prototype.getCapacity = function () {
  56748. return this._capacity;
  56749. };
  56750. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56751. /**
  56752. * Gets or set the number of active particles
  56753. */
  56754. get: function () {
  56755. return this._activeCount;
  56756. },
  56757. set: function (value) {
  56758. this._activeCount = Math.min(value, this._capacity);
  56759. },
  56760. enumerable: true,
  56761. configurable: true
  56762. });
  56763. /**
  56764. * Is this system ready to be used/rendered
  56765. * @return true if the system is ready
  56766. */
  56767. GPUParticleSystem.prototype.isReady = function () {
  56768. if (!this._updateEffect) {
  56769. this._recreateUpdateEffect();
  56770. this._recreateRenderEffect();
  56771. return false;
  56772. }
  56773. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56774. return false;
  56775. }
  56776. return true;
  56777. };
  56778. /**
  56779. * Gets Wether the system has been started.
  56780. * @returns True if it has been started, otherwise false.
  56781. */
  56782. GPUParticleSystem.prototype.isStarted = function () {
  56783. return this._started;
  56784. };
  56785. /**
  56786. * Starts the particle system and begins to emit.
  56787. */
  56788. GPUParticleSystem.prototype.start = function () {
  56789. this._started = true;
  56790. this._stopped = false;
  56791. };
  56792. /**
  56793. * Stops the particle system.
  56794. */
  56795. GPUParticleSystem.prototype.stop = function () {
  56796. this._stopped = true;
  56797. };
  56798. /**
  56799. * Remove all active particles
  56800. */
  56801. GPUParticleSystem.prototype.reset = function () {
  56802. this._releaseBuffers();
  56803. this._releaseVAOs();
  56804. this._currentActiveCount = 0;
  56805. this._targetIndex = 0;
  56806. };
  56807. /**
  56808. * Returns the string "GPUParticleSystem"
  56809. * @returns a string containing the class name
  56810. */
  56811. GPUParticleSystem.prototype.getClassName = function () {
  56812. return "GPUParticleSystem";
  56813. };
  56814. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56815. var updateVertexBuffers = {};
  56816. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56817. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56818. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56819. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56820. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56821. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56822. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56823. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56824. this._engine.bindArrayBuffer(null);
  56825. return vao;
  56826. };
  56827. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56828. var renderVertexBuffers = {};
  56829. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56830. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56831. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56832. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56833. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56834. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56835. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56836. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56837. this._engine.bindArrayBuffer(null);
  56838. return vao;
  56839. };
  56840. GPUParticleSystem.prototype._initialize = function (force) {
  56841. if (force === void 0) { force = false; }
  56842. if (this._buffer0 && !force) {
  56843. return;
  56844. }
  56845. var engine = this._scene.getEngine();
  56846. var data = new Array();
  56847. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56848. // position
  56849. data.push(0.0);
  56850. data.push(0.0);
  56851. data.push(0.0);
  56852. // Age and life
  56853. data.push(0.0); // create the particle as a dead one to create a new one at start
  56854. data.push(0.0);
  56855. // Seed
  56856. data.push(Math.random());
  56857. // Size
  56858. data.push(0.0);
  56859. // color
  56860. data.push(0.0);
  56861. data.push(0.0);
  56862. data.push(0.0);
  56863. data.push(0.0);
  56864. // direction
  56865. data.push(0.0);
  56866. data.push(0.0);
  56867. data.push(0.0);
  56868. }
  56869. // Sprite data
  56870. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56871. -0.5, 0.5, 0, 1,
  56872. -0.5, -0.5, 0, 0,
  56873. 0.5, -0.5, 1, 0]);
  56874. // Buffers
  56875. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56876. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56877. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56878. // Update VAO
  56879. this._updateVAO = [];
  56880. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56881. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56882. // Render VAO
  56883. this._renderVAO = [];
  56884. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56885. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56886. // Links
  56887. this._sourceBuffer = this._buffer0;
  56888. this._targetBuffer = this._buffer1;
  56889. };
  56890. /** @ignore */
  56891. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56892. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56893. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56894. return;
  56895. }
  56896. this._updateEffectOptions.defines = defines;
  56897. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56898. };
  56899. /** @ignore */
  56900. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56901. var defines = "";
  56902. if (this._scene.clipPlane) {
  56903. defines = "\n#define CLIPPLANE";
  56904. }
  56905. if (this._renderEffect && this._renderEffect.defines === defines) {
  56906. return;
  56907. }
  56908. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56909. };
  56910. /**
  56911. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56912. */
  56913. GPUParticleSystem.prototype.animate = function () {
  56914. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56915. this._actualFrame += this._timeDelta;
  56916. if (!this._stopped) {
  56917. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56918. this.stop();
  56919. }
  56920. }
  56921. };
  56922. /**
  56923. * Renders the particle system in its current state.
  56924. * @returns the current number of particles
  56925. */
  56926. GPUParticleSystem.prototype.render = function () {
  56927. if (!this._started) {
  56928. return 0;
  56929. }
  56930. this._recreateUpdateEffect();
  56931. this._recreateRenderEffect();
  56932. if (!this.isReady()) {
  56933. return 0;
  56934. }
  56935. if (this._currentRenderId === this._scene.getRenderId()) {
  56936. return 0;
  56937. }
  56938. this._currentRenderId = this._scene.getRenderId();
  56939. // Get everything ready to render
  56940. this._initialize();
  56941. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56942. // Enable update effect
  56943. this._engine.enableEffect(this._updateEffect);
  56944. this._engine.setState(false);
  56945. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56946. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56947. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56948. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56949. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56950. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56951. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56952. this._updateEffect.setDirectColor4("color1", this.color1);
  56953. this._updateEffect.setDirectColor4("color2", this.color2);
  56954. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56955. this._updateEffect.setVector3("gravity", this.gravity);
  56956. if (this.particleEmitterType) {
  56957. this.particleEmitterType.applyToShader(this._updateEffect);
  56958. }
  56959. var emitterWM;
  56960. if (this.emitter.position) {
  56961. var emitterMesh = this.emitter;
  56962. emitterWM = emitterMesh.getWorldMatrix();
  56963. }
  56964. else {
  56965. var emitterPosition = this.emitter;
  56966. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56967. }
  56968. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56969. // Bind source VAO
  56970. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56971. // Update
  56972. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56973. this._engine.setRasterizerState(false);
  56974. this._engine.beginTransformFeedback();
  56975. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56976. this._engine.endTransformFeedback();
  56977. this._engine.setRasterizerState(true);
  56978. this._engine.bindTransformFeedbackBuffer(null);
  56979. // Enable render effect
  56980. this._engine.enableEffect(this._renderEffect);
  56981. var viewMatrix = this._scene.getViewMatrix();
  56982. this._renderEffect.setMatrix("view", viewMatrix);
  56983. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56984. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56985. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56986. if (this._scene.clipPlane) {
  56987. var clipPlane = this._scene.clipPlane;
  56988. var invView = viewMatrix.clone();
  56989. invView.invert();
  56990. this._renderEffect.setMatrix("invView", invView);
  56991. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56992. }
  56993. // Draw order
  56994. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56995. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56996. }
  56997. else {
  56998. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56999. }
  57000. if (this.forceDepthWrite) {
  57001. this._engine.setDepthWrite(true);
  57002. }
  57003. // Bind source VAO
  57004. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57005. // Render
  57006. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57007. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57008. // Switch VAOs
  57009. this._targetIndex++;
  57010. if (this._targetIndex === 2) {
  57011. this._targetIndex = 0;
  57012. }
  57013. // Switch buffers
  57014. var tmpBuffer = this._sourceBuffer;
  57015. this._sourceBuffer = this._targetBuffer;
  57016. this._targetBuffer = tmpBuffer;
  57017. return this._currentActiveCount;
  57018. };
  57019. /**
  57020. * Rebuilds the particle system
  57021. */
  57022. GPUParticleSystem.prototype.rebuild = function () {
  57023. this._initialize(true);
  57024. };
  57025. GPUParticleSystem.prototype._releaseBuffers = function () {
  57026. if (this._buffer0) {
  57027. this._buffer0.dispose();
  57028. this._buffer0 = null;
  57029. }
  57030. if (this._buffer1) {
  57031. this._buffer1.dispose();
  57032. this._buffer1 = null;
  57033. }
  57034. if (this._spriteBuffer) {
  57035. this._spriteBuffer.dispose();
  57036. this._spriteBuffer = null;
  57037. }
  57038. };
  57039. GPUParticleSystem.prototype._releaseVAOs = function () {
  57040. if (!this._updateVAO) {
  57041. return;
  57042. }
  57043. for (var index = 0; index < this._updateVAO.length; index++) {
  57044. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57045. }
  57046. this._updateVAO = [];
  57047. for (var index = 0; index < this._renderVAO.length; index++) {
  57048. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57049. }
  57050. this._renderVAO = [];
  57051. };
  57052. /**
  57053. * Disposes the particle system and free the associated resources
  57054. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57055. */
  57056. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57057. if (disposeTexture === void 0) { disposeTexture = true; }
  57058. var index = this._scene.particleSystems.indexOf(this);
  57059. if (index > -1) {
  57060. this._scene.particleSystems.splice(index, 1);
  57061. }
  57062. this._releaseBuffers();
  57063. this._releaseVAOs();
  57064. if (this._randomTexture) {
  57065. this._randomTexture.dispose();
  57066. this._randomTexture = null;
  57067. }
  57068. if (disposeTexture && this.particleTexture) {
  57069. this.particleTexture.dispose();
  57070. this.particleTexture = null;
  57071. }
  57072. // Callback
  57073. this.onDisposeObservable.notifyObservers(this);
  57074. this.onDisposeObservable.clear();
  57075. };
  57076. /**
  57077. * Clones the particle system.
  57078. * @param name The name of the cloned object
  57079. * @param newEmitter The new emitter to use
  57080. * @returns the cloned particle system
  57081. */
  57082. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57083. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57084. BABYLON.Tools.DeepCopy(this, result);
  57085. if (newEmitter === undefined) {
  57086. newEmitter = this.emitter;
  57087. }
  57088. result.emitter = newEmitter;
  57089. if (this.particleTexture) {
  57090. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57091. }
  57092. return result;
  57093. };
  57094. /**
  57095. * Serializes the particle system to a JSON object.
  57096. * @returns the JSON object
  57097. */
  57098. GPUParticleSystem.prototype.serialize = function () {
  57099. var serializationObject = {};
  57100. serializationObject.name = this.name;
  57101. serializationObject.id = this.id;
  57102. // Emitter
  57103. if (this.emitter.position) {
  57104. var emitterMesh = this.emitter;
  57105. serializationObject.emitterId = emitterMesh.id;
  57106. }
  57107. else {
  57108. var emitterPosition = this.emitter;
  57109. serializationObject.emitter = emitterPosition.asArray();
  57110. }
  57111. serializationObject.capacity = this.getCapacity();
  57112. if (this.particleTexture) {
  57113. serializationObject.textureName = this.particleTexture.name;
  57114. }
  57115. // Animations
  57116. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57117. // Particle system
  57118. serializationObject.activeParticleCount = this.activeParticleCount;
  57119. serializationObject.randomTextureSize = this._randomTextureSize;
  57120. serializationObject.minSize = this.minSize;
  57121. serializationObject.maxSize = this.maxSize;
  57122. serializationObject.minEmitPower = this.minEmitPower;
  57123. serializationObject.maxEmitPower = this.maxEmitPower;
  57124. serializationObject.minLifeTime = this.minLifeTime;
  57125. serializationObject.maxLifeTime = this.maxLifeTime;
  57126. serializationObject.emitRate = this.emitRate;
  57127. serializationObject.gravity = this.gravity.asArray();
  57128. serializationObject.color1 = this.color1.asArray();
  57129. serializationObject.color2 = this.color2.asArray();
  57130. serializationObject.colorDead = this.colorDead.asArray();
  57131. serializationObject.updateSpeed = this.updateSpeed;
  57132. serializationObject.targetStopDuration = this.targetStopDuration;
  57133. serializationObject.blendMode = this.blendMode;
  57134. // Emitter
  57135. if (this.particleEmitterType) {
  57136. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57137. }
  57138. return serializationObject;
  57139. };
  57140. /**
  57141. * Parses a JSON object to create a GPU particle system.
  57142. * @param parsedParticleSystem The JSON object to parse
  57143. * @param scene The scene to create the particle system in
  57144. * @param rootUrl The root url to use to load external dependencies like texture
  57145. * @returns the parsed GPU particle system
  57146. */
  57147. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57148. var name = parsedParticleSystem.name;
  57149. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57150. if (parsedParticleSystem.id) {
  57151. particleSystem.id = parsedParticleSystem.id;
  57152. }
  57153. // Texture
  57154. if (parsedParticleSystem.textureName) {
  57155. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57156. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57157. }
  57158. // Emitter
  57159. if (parsedParticleSystem.emitterId) {
  57160. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57161. }
  57162. else {
  57163. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57164. }
  57165. // Animations
  57166. if (parsedParticleSystem.animations) {
  57167. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57168. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57169. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57170. }
  57171. }
  57172. // Particle system
  57173. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57174. particleSystem.minSize = parsedParticleSystem.minSize;
  57175. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57176. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57177. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57178. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57179. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57180. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57181. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57182. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57183. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57184. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57185. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57186. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57187. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57188. // Emitter
  57189. if (parsedParticleSystem.particleEmitterType) {
  57190. var emitterType = void 0;
  57191. switch (parsedParticleSystem.particleEmitterType.type) {
  57192. case "SphereEmitter":
  57193. emitterType = new BABYLON.SphereParticleEmitter();
  57194. break;
  57195. case "SphereDirectedParticleEmitter":
  57196. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57197. break;
  57198. case "ConeEmitter":
  57199. emitterType = new BABYLON.ConeParticleEmitter();
  57200. break;
  57201. case "BoxEmitter":
  57202. default:
  57203. emitterType = new BABYLON.BoxParticleEmitter();
  57204. break;
  57205. }
  57206. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57207. particleSystem.particleEmitterType = emitterType;
  57208. }
  57209. return particleSystem;
  57210. };
  57211. return GPUParticleSystem;
  57212. }());
  57213. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57214. })(BABYLON || (BABYLON = {}));
  57215. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57216. var BABYLON;
  57217. (function (BABYLON) {
  57218. /**
  57219. * Represents one particle of a solid particle system.
  57220. */
  57221. var SolidParticle = /** @class */ (function () {
  57222. /**
  57223. * Creates a Solid Particle object.
  57224. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57225. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57226. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57227. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57228. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57229. * @param shapeId (integer) is the model shape identifier in the SPS.
  57230. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57231. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57232. */
  57233. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57234. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57235. /**
  57236. * particle global index
  57237. */
  57238. this.idx = 0;
  57239. /**
  57240. * The color of the particle
  57241. */
  57242. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57243. /**
  57244. * The world space position of the particle.
  57245. */
  57246. this.position = BABYLON.Vector3.Zero();
  57247. /**
  57248. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57249. */
  57250. this.rotation = BABYLON.Vector3.Zero();
  57251. /**
  57252. * The scaling of the particle.
  57253. */
  57254. this.scaling = BABYLON.Vector3.One();
  57255. /**
  57256. * The uvs of the particle.
  57257. */
  57258. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57259. /**
  57260. * The current speed of the particle.
  57261. */
  57262. this.velocity = BABYLON.Vector3.Zero();
  57263. /**
  57264. * The pivot point in the particle local space.
  57265. */
  57266. this.pivot = BABYLON.Vector3.Zero();
  57267. /**
  57268. * Must the particle be translated from its pivot point in its local space ?
  57269. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57270. * Default : false
  57271. */
  57272. this.translateFromPivot = false;
  57273. /**
  57274. * Is the particle active or not ?
  57275. */
  57276. this.alive = true;
  57277. /**
  57278. * Is the particle visible or not ?
  57279. */
  57280. this.isVisible = true;
  57281. /**
  57282. * Index of this particle in the global "positions" array (Internal use)
  57283. */
  57284. this._pos = 0;
  57285. /**
  57286. * Index of this particle in the global "indices" array (Internal use)
  57287. */
  57288. this._ind = 0;
  57289. /**
  57290. * ModelShape id of this particle
  57291. */
  57292. this.shapeId = 0;
  57293. /**
  57294. * Index of the particle in its shape id (Internal use)
  57295. */
  57296. this.idxInShape = 0;
  57297. /**
  57298. * Still set as invisible in order to skip useless computations (Internal use)
  57299. */
  57300. this._stillInvisible = false;
  57301. /**
  57302. * Last computed particle rotation matrix
  57303. */
  57304. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57305. /**
  57306. * Parent particle Id, if any.
  57307. * Default null.
  57308. */
  57309. this.parentId = null;
  57310. /**
  57311. * Internal global position in the SPS.
  57312. */
  57313. this._globalPosition = BABYLON.Vector3.Zero();
  57314. this.idx = particleIndex;
  57315. this._pos = positionIndex;
  57316. this._ind = indiceIndex;
  57317. this._model = model;
  57318. this.shapeId = shapeId;
  57319. this.idxInShape = idxInShape;
  57320. this._sps = sps;
  57321. if (modelBoundingInfo) {
  57322. this._modelBoundingInfo = modelBoundingInfo;
  57323. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57324. }
  57325. }
  57326. Object.defineProperty(SolidParticle.prototype, "scale", {
  57327. /**
  57328. * Legacy support, changed scale to scaling
  57329. */
  57330. get: function () {
  57331. return this.scaling;
  57332. },
  57333. /**
  57334. * Legacy support, changed scale to scaling
  57335. */
  57336. set: function (scale) {
  57337. this.scaling = scale;
  57338. },
  57339. enumerable: true,
  57340. configurable: true
  57341. });
  57342. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57343. /**
  57344. * Legacy support, changed quaternion to rotationQuaternion
  57345. */
  57346. get: function () {
  57347. return this.rotationQuaternion;
  57348. },
  57349. /**
  57350. * Legacy support, changed quaternion to rotationQuaternion
  57351. */
  57352. set: function (q) {
  57353. this.rotationQuaternion = q;
  57354. },
  57355. enumerable: true,
  57356. configurable: true
  57357. });
  57358. /**
  57359. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57360. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57361. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57362. * @returns true if it intersects
  57363. */
  57364. SolidParticle.prototype.intersectsMesh = function (target) {
  57365. if (!this._boundingInfo || !target._boundingInfo) {
  57366. return false;
  57367. }
  57368. if (this._sps._bSphereOnly) {
  57369. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57370. }
  57371. return this._boundingInfo.intersects(target._boundingInfo, false);
  57372. };
  57373. return SolidParticle;
  57374. }());
  57375. BABYLON.SolidParticle = SolidParticle;
  57376. /**
  57377. * Represents the shape of the model used by one particle of a solid particle system.
  57378. * SPS internal tool, don't use it manually.
  57379. */
  57380. var ModelShape = /** @class */ (function () {
  57381. /**
  57382. * 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.
  57383. * SPS internal tool, don't use it manually.
  57384. * @ignore
  57385. */
  57386. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57387. /**
  57388. * length of the shape in the model indices array (internal use)
  57389. */
  57390. this._indicesLength = 0;
  57391. this.shapeID = id;
  57392. this._shape = shape;
  57393. this._indicesLength = indicesLength;
  57394. this._shapeUV = shapeUV;
  57395. this._positionFunction = posFunction;
  57396. this._vertexFunction = vtxFunction;
  57397. }
  57398. return ModelShape;
  57399. }());
  57400. BABYLON.ModelShape = ModelShape;
  57401. /**
  57402. * Represents a Depth Sorted Particle in the solid particle system.
  57403. */
  57404. var DepthSortedParticle = /** @class */ (function () {
  57405. function DepthSortedParticle() {
  57406. /**
  57407. * Index of the particle in the "indices" array
  57408. */
  57409. this.ind = 0;
  57410. /**
  57411. * Length of the particle shape in the "indices" array
  57412. */
  57413. this.indicesLength = 0;
  57414. /**
  57415. * Squared distance from the particle to the camera
  57416. */
  57417. this.sqDistance = 0.0;
  57418. }
  57419. return DepthSortedParticle;
  57420. }());
  57421. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57422. })(BABYLON || (BABYLON = {}));
  57423. //# sourceMappingURL=babylon.solidParticle.js.map
  57424. var BABYLON;
  57425. (function (BABYLON) {
  57426. /**
  57427. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57428. *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.
  57429. * The SPS is also a particle system. It provides some methods to manage the particles.
  57430. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57431. *
  57432. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57433. */
  57434. var SolidParticleSystem = /** @class */ (function () {
  57435. /**
  57436. * Creates a SPS (Solid Particle System) object.
  57437. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57438. * @param scene (Scene) is the scene in which the SPS is added.
  57439. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57440. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57441. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57442. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57443. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57444. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57445. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57446. */
  57447. function SolidParticleSystem(name, scene, options) {
  57448. /**
  57449. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57450. * Example : var p = SPS.particles[i];
  57451. */
  57452. this.particles = new Array();
  57453. /**
  57454. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57455. */
  57456. this.nbParticles = 0;
  57457. /**
  57458. * If the particles must ever face the camera (default false). Useful for planar particles.
  57459. */
  57460. this.billboard = false;
  57461. /**
  57462. * Recompute normals when adding a shape
  57463. */
  57464. this.recomputeNormals = true;
  57465. /**
  57466. * This a counter ofr your own usage. It's not set by any SPS functions.
  57467. */
  57468. this.counter = 0;
  57469. /**
  57470. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57471. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57472. */
  57473. this.vars = {};
  57474. /**
  57475. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57476. */
  57477. this._bSphereOnly = false;
  57478. /**
  57479. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57480. */
  57481. this._bSphereRadiusFactor = 1.0;
  57482. this._positions = new Array();
  57483. this._indices = new Array();
  57484. this._normals = new Array();
  57485. this._colors = new Array();
  57486. this._uvs = new Array();
  57487. this._index = 0; // indices index
  57488. this._updatable = true;
  57489. this._pickable = false;
  57490. this._isVisibilityBoxLocked = false;
  57491. this._alwaysVisible = false;
  57492. this._depthSort = false;
  57493. this._shapeCounter = 0;
  57494. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57495. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57496. this._computeParticleColor = true;
  57497. this._computeParticleTexture = true;
  57498. this._computeParticleRotation = true;
  57499. this._computeParticleVertex = false;
  57500. this._computeBoundingBox = false;
  57501. this._depthSortParticles = true;
  57502. this._cam_axisZ = BABYLON.Vector3.Zero();
  57503. this._cam_axisY = BABYLON.Vector3.Zero();
  57504. this._cam_axisX = BABYLON.Vector3.Zero();
  57505. this._axisZ = BABYLON.Axis.Z;
  57506. this._camDir = BABYLON.Vector3.Zero();
  57507. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57508. this._rotMatrix = new BABYLON.Matrix();
  57509. this._invertMatrix = new BABYLON.Matrix();
  57510. this._rotated = BABYLON.Vector3.Zero();
  57511. this._quaternion = new BABYLON.Quaternion();
  57512. this._vertex = BABYLON.Vector3.Zero();
  57513. this._normal = BABYLON.Vector3.Zero();
  57514. this._yaw = 0.0;
  57515. this._pitch = 0.0;
  57516. this._roll = 0.0;
  57517. this._halfroll = 0.0;
  57518. this._halfpitch = 0.0;
  57519. this._halfyaw = 0.0;
  57520. this._sinRoll = 0.0;
  57521. this._cosRoll = 0.0;
  57522. this._sinPitch = 0.0;
  57523. this._cosPitch = 0.0;
  57524. this._sinYaw = 0.0;
  57525. this._cosYaw = 0.0;
  57526. this._mustUnrotateFixedNormals = false;
  57527. this._minimum = BABYLON.Vector3.Zero();
  57528. this._maximum = BABYLON.Vector3.Zero();
  57529. this._minBbox = BABYLON.Vector3.Zero();
  57530. this._maxBbox = BABYLON.Vector3.Zero();
  57531. this._particlesIntersect = false;
  57532. this._depthSortFunction = function (p1, p2) {
  57533. return (p2.sqDistance - p1.sqDistance);
  57534. };
  57535. this._needs32Bits = false;
  57536. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57537. this._scaledPivot = BABYLON.Vector3.Zero();
  57538. this._particleHasParent = false;
  57539. this.name = name;
  57540. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57541. this._camera = scene.activeCamera;
  57542. this._pickable = options ? options.isPickable : false;
  57543. this._depthSort = options ? options.enableDepthSort : false;
  57544. this._particlesIntersect = options ? options.particleIntersection : false;
  57545. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57546. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57547. if (options && options.updatable) {
  57548. this._updatable = options.updatable;
  57549. }
  57550. else {
  57551. this._updatable = true;
  57552. }
  57553. if (this._pickable) {
  57554. this.pickedParticles = [];
  57555. }
  57556. if (this._depthSort) {
  57557. this.depthSortedParticles = [];
  57558. }
  57559. }
  57560. /**
  57561. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57562. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57563. * @returns the created mesh
  57564. */
  57565. SolidParticleSystem.prototype.buildMesh = function () {
  57566. if (this.nbParticles === 0) {
  57567. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57568. this.addShape(triangle, 1);
  57569. triangle.dispose();
  57570. }
  57571. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57572. this._positions32 = new Float32Array(this._positions);
  57573. this._uvs32 = new Float32Array(this._uvs);
  57574. this._colors32 = new Float32Array(this._colors);
  57575. if (this.recomputeNormals) {
  57576. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57577. }
  57578. this._normals32 = new Float32Array(this._normals);
  57579. this._fixedNormal32 = new Float32Array(this._normals);
  57580. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57581. this._unrotateFixedNormals();
  57582. }
  57583. var vertexData = new BABYLON.VertexData();
  57584. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57585. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57586. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57587. if (this._uvs32) {
  57588. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57589. ;
  57590. }
  57591. if (this._colors32) {
  57592. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57593. }
  57594. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57595. vertexData.applyToMesh(mesh, this._updatable);
  57596. this.mesh = mesh;
  57597. this.mesh.isPickable = this._pickable;
  57598. // free memory
  57599. if (!this._depthSort) {
  57600. this._indices = null;
  57601. }
  57602. this._positions = null;
  57603. this._normals = null;
  57604. this._uvs = null;
  57605. this._colors = null;
  57606. if (!this._updatable) {
  57607. this.particles.length = 0;
  57608. }
  57609. return mesh;
  57610. };
  57611. /**
  57612. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57613. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57614. * Thus the particles generated from `digest()` have their property `position` set yet.
  57615. * @param mesh ( Mesh ) is the mesh to be digested
  57616. * @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
  57617. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57618. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57619. * @returns the current SPS
  57620. */
  57621. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57622. var size = (options && options.facetNb) || 1;
  57623. var number = (options && options.number) || 0;
  57624. var delta = (options && options.delta) || 0;
  57625. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57626. var meshInd = mesh.getIndices();
  57627. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57628. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57629. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57630. var f = 0; // facet counter
  57631. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57632. // compute size from number
  57633. if (number) {
  57634. number = (number > totalFacets) ? totalFacets : number;
  57635. size = Math.round(totalFacets / number);
  57636. delta = 0;
  57637. }
  57638. else {
  57639. size = (size > totalFacets) ? totalFacets : size;
  57640. }
  57641. var facetPos = []; // submesh positions
  57642. var facetInd = []; // submesh indices
  57643. var facetUV = []; // submesh UV
  57644. var facetCol = []; // submesh colors
  57645. var barycenter = BABYLON.Vector3.Zero();
  57646. var sizeO = size;
  57647. while (f < totalFacets) {
  57648. size = sizeO + Math.floor((1 + delta) * Math.random());
  57649. if (f > totalFacets - size) {
  57650. size = totalFacets - f;
  57651. }
  57652. // reset temp arrays
  57653. facetPos.length = 0;
  57654. facetInd.length = 0;
  57655. facetUV.length = 0;
  57656. facetCol.length = 0;
  57657. // iterate over "size" facets
  57658. var fi = 0;
  57659. for (var j = f * 3; j < (f + size) * 3; j++) {
  57660. facetInd.push(fi);
  57661. var i = meshInd[j];
  57662. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57663. if (meshUV) {
  57664. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57665. }
  57666. if (meshCol) {
  57667. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57668. }
  57669. fi++;
  57670. }
  57671. // create a model shape for each single particle
  57672. var idx = this.nbParticles;
  57673. var shape = this._posToShape(facetPos);
  57674. var shapeUV = this._uvsToShapeUV(facetUV);
  57675. // compute the barycenter of the shape
  57676. var v;
  57677. for (v = 0; v < shape.length; v++) {
  57678. barycenter.addInPlace(shape[v]);
  57679. }
  57680. barycenter.scaleInPlace(1 / shape.length);
  57681. // shift the shape from its barycenter to the origin
  57682. for (v = 0; v < shape.length; v++) {
  57683. shape[v].subtractInPlace(barycenter);
  57684. }
  57685. var bInfo;
  57686. if (this._particlesIntersect) {
  57687. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57688. }
  57689. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57690. // add the particle in the SPS
  57691. var currentPos = this._positions.length;
  57692. var currentInd = this._indices.length;
  57693. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57694. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57695. // initialize the particle position
  57696. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57697. this._index += shape.length;
  57698. idx++;
  57699. this.nbParticles++;
  57700. this._shapeCounter++;
  57701. f += size;
  57702. }
  57703. return this;
  57704. };
  57705. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57706. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57707. var index = 0;
  57708. var idx = 0;
  57709. for (var p = 0; p < this.particles.length; p++) {
  57710. this._particle = this.particles[p];
  57711. this._shape = this._particle._model._shape;
  57712. if (this._particle.rotationQuaternion) {
  57713. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57714. }
  57715. else {
  57716. this._yaw = this._particle.rotation.y;
  57717. this._pitch = this._particle.rotation.x;
  57718. this._roll = this._particle.rotation.z;
  57719. this._quaternionRotationYPR();
  57720. }
  57721. this._quaternionToRotationMatrix();
  57722. this._rotMatrix.invertToRef(this._invertMatrix);
  57723. for (var pt = 0; pt < this._shape.length; pt++) {
  57724. idx = index + pt * 3;
  57725. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57726. this._fixedNormal32[idx] = this._normal.x;
  57727. this._fixedNormal32[idx + 1] = this._normal.y;
  57728. this._fixedNormal32[idx + 2] = this._normal.z;
  57729. }
  57730. index = idx + 3;
  57731. }
  57732. };
  57733. //reset copy
  57734. SolidParticleSystem.prototype._resetCopy = function () {
  57735. this._copy.position.x = 0;
  57736. this._copy.position.y = 0;
  57737. this._copy.position.z = 0;
  57738. this._copy.rotation.x = 0;
  57739. this._copy.rotation.y = 0;
  57740. this._copy.rotation.z = 0;
  57741. this._copy.rotationQuaternion = null;
  57742. this._copy.scaling.x = 1.0;
  57743. this._copy.scaling.y = 1.0;
  57744. this._copy.scaling.z = 1.0;
  57745. this._copy.uvs.x = 0;
  57746. this._copy.uvs.y = 0;
  57747. this._copy.uvs.z = 1.0;
  57748. this._copy.uvs.w = 1.0;
  57749. this._copy.color = null;
  57750. this._copy.translateFromPivot = false;
  57751. };
  57752. // _meshBuilder : inserts the shape model in the global SPS mesh
  57753. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57754. var i;
  57755. var u = 0;
  57756. var c = 0;
  57757. var n = 0;
  57758. this._resetCopy();
  57759. if (options && options.positionFunction) { // call to custom positionFunction
  57760. options.positionFunction(this._copy, idx, idxInShape);
  57761. this._mustUnrotateFixedNormals = true;
  57762. }
  57763. if (this._copy.rotationQuaternion) {
  57764. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57765. }
  57766. else {
  57767. this._yaw = this._copy.rotation.y;
  57768. this._pitch = this._copy.rotation.x;
  57769. this._roll = this._copy.rotation.z;
  57770. this._quaternionRotationYPR();
  57771. }
  57772. this._quaternionToRotationMatrix();
  57773. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57774. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57775. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57776. if (this._copy.translateFromPivot) {
  57777. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57778. }
  57779. else {
  57780. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57781. }
  57782. for (i = 0; i < shape.length; i++) {
  57783. this._vertex.x = shape[i].x;
  57784. this._vertex.y = shape[i].y;
  57785. this._vertex.z = shape[i].z;
  57786. if (options && options.vertexFunction) {
  57787. options.vertexFunction(this._copy, this._vertex, i);
  57788. }
  57789. this._vertex.x *= this._copy.scaling.x;
  57790. this._vertex.y *= this._copy.scaling.y;
  57791. this._vertex.z *= this._copy.scaling.z;
  57792. this._vertex.x -= this._scaledPivot.x;
  57793. this._vertex.y -= this._scaledPivot.y;
  57794. this._vertex.z -= this._scaledPivot.z;
  57795. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57796. this._rotated.addInPlace(this._pivotBackTranslation);
  57797. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57798. if (meshUV) {
  57799. 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);
  57800. u += 2;
  57801. }
  57802. if (this._copy.color) {
  57803. this._color = this._copy.color;
  57804. }
  57805. else if (meshCol && meshCol[c] !== undefined) {
  57806. this._color.r = meshCol[c];
  57807. this._color.g = meshCol[c + 1];
  57808. this._color.b = meshCol[c + 2];
  57809. this._color.a = meshCol[c + 3];
  57810. }
  57811. else {
  57812. this._color.r = 1.0;
  57813. this._color.g = 1.0;
  57814. this._color.b = 1.0;
  57815. this._color.a = 1.0;
  57816. }
  57817. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57818. c += 4;
  57819. if (!this.recomputeNormals && meshNor) {
  57820. this._normal.x = meshNor[n];
  57821. this._normal.y = meshNor[n + 1];
  57822. this._normal.z = meshNor[n + 2];
  57823. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57824. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57825. n += 3;
  57826. }
  57827. }
  57828. for (i = 0; i < meshInd.length; i++) {
  57829. var current_ind = p + meshInd[i];
  57830. indices.push(current_ind);
  57831. if (current_ind > 65535) {
  57832. this._needs32Bits = true;
  57833. }
  57834. }
  57835. if (this._pickable) {
  57836. var nbfaces = meshInd.length / 3;
  57837. for (i = 0; i < nbfaces; i++) {
  57838. this.pickedParticles.push({ idx: idx, faceId: i });
  57839. }
  57840. }
  57841. if (this._depthSort) {
  57842. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57843. }
  57844. return this._copy;
  57845. };
  57846. // returns a shape array from positions array
  57847. SolidParticleSystem.prototype._posToShape = function (positions) {
  57848. var shape = [];
  57849. for (var i = 0; i < positions.length; i += 3) {
  57850. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57851. }
  57852. return shape;
  57853. };
  57854. // returns a shapeUV array from a Vector4 uvs
  57855. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57856. var shapeUV = [];
  57857. if (uvs) {
  57858. for (var i = 0; i < uvs.length; i++)
  57859. shapeUV.push(uvs[i]);
  57860. }
  57861. return shapeUV;
  57862. };
  57863. // adds a new particle object in the particles array
  57864. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57865. if (bInfo === void 0) { bInfo = null; }
  57866. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57867. this.particles.push(sp);
  57868. return sp;
  57869. };
  57870. /**
  57871. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57872. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57873. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57874. * @param nb (positive integer) the number of particles to be created from this model
  57875. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57876. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57877. * @returns the number of shapes in the system
  57878. */
  57879. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57880. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57881. var meshInd = mesh.getIndices();
  57882. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57883. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57884. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57885. var bbInfo;
  57886. if (this._particlesIntersect) {
  57887. bbInfo = mesh.getBoundingInfo();
  57888. }
  57889. var shape = this._posToShape(meshPos);
  57890. var shapeUV = this._uvsToShapeUV(meshUV);
  57891. var posfunc = options ? options.positionFunction : null;
  57892. var vtxfunc = options ? options.vertexFunction : null;
  57893. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57894. // particles
  57895. var sp;
  57896. var currentCopy;
  57897. var idx = this.nbParticles;
  57898. for (var i = 0; i < nb; i++) {
  57899. var currentPos = this._positions.length;
  57900. var currentInd = this._indices.length;
  57901. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57902. if (this._updatable) {
  57903. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57904. sp.position.copyFrom(currentCopy.position);
  57905. sp.rotation.copyFrom(currentCopy.rotation);
  57906. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57907. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57908. }
  57909. if (currentCopy.color && sp.color) {
  57910. sp.color.copyFrom(currentCopy.color);
  57911. }
  57912. sp.scaling.copyFrom(currentCopy.scaling);
  57913. sp.uvs.copyFrom(currentCopy.uvs);
  57914. }
  57915. this._index += shape.length;
  57916. idx++;
  57917. }
  57918. this.nbParticles += nb;
  57919. this._shapeCounter++;
  57920. return this._shapeCounter - 1;
  57921. };
  57922. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57923. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57924. this._resetCopy();
  57925. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57926. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57927. }
  57928. if (this._copy.rotationQuaternion) {
  57929. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57930. }
  57931. else {
  57932. this._yaw = this._copy.rotation.y;
  57933. this._pitch = this._copy.rotation.x;
  57934. this._roll = this._copy.rotation.z;
  57935. this._quaternionRotationYPR();
  57936. }
  57937. this._quaternionToRotationMatrix();
  57938. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57939. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57940. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57941. if (this._copy.translateFromPivot) {
  57942. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57943. }
  57944. else {
  57945. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57946. }
  57947. this._shape = particle._model._shape;
  57948. for (var pt = 0; pt < this._shape.length; pt++) {
  57949. this._vertex.x = this._shape[pt].x;
  57950. this._vertex.y = this._shape[pt].y;
  57951. this._vertex.z = this._shape[pt].z;
  57952. if (particle._model._vertexFunction) {
  57953. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57954. }
  57955. this._vertex.x *= this._copy.scaling.x;
  57956. this._vertex.y *= this._copy.scaling.y;
  57957. this._vertex.z *= this._copy.scaling.z;
  57958. this._vertex.x -= this._scaledPivot.x;
  57959. this._vertex.y -= this._scaledPivot.y;
  57960. this._vertex.z -= this._scaledPivot.z;
  57961. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57962. this._rotated.addInPlace(this._pivotBackTranslation);
  57963. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57964. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57965. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57966. }
  57967. particle.position.x = 0.0;
  57968. particle.position.y = 0.0;
  57969. particle.position.z = 0.0;
  57970. particle.rotation.x = 0.0;
  57971. particle.rotation.y = 0.0;
  57972. particle.rotation.z = 0.0;
  57973. particle.rotationQuaternion = null;
  57974. particle.scaling.x = 1.0;
  57975. particle.scaling.y = 1.0;
  57976. particle.scaling.z = 1.0;
  57977. particle.uvs.x = 0.0;
  57978. particle.uvs.y = 0.0;
  57979. particle.uvs.z = 1.0;
  57980. particle.uvs.w = 1.0;
  57981. particle.pivot.x = 0.0;
  57982. particle.pivot.y = 0.0;
  57983. particle.pivot.z = 0.0;
  57984. particle.translateFromPivot = false;
  57985. particle.parentId = null;
  57986. };
  57987. /**
  57988. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57989. * @returns the SPS.
  57990. */
  57991. SolidParticleSystem.prototype.rebuildMesh = function () {
  57992. for (var p = 0; p < this.particles.length; p++) {
  57993. this._rebuildParticle(this.particles[p]);
  57994. }
  57995. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57996. return this;
  57997. };
  57998. /**
  57999. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58000. * This method calls `updateParticle()` for each particle of the SPS.
  58001. * For an animated SPS, it is usually called within the render loop.
  58002. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58003. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58004. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58005. * @returns the SPS.
  58006. */
  58007. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58008. if (start === void 0) { start = 0; }
  58009. if (end === void 0) { end = this.nbParticles - 1; }
  58010. if (update === void 0) { update = true; }
  58011. if (!this._updatable) {
  58012. return this;
  58013. }
  58014. // custom beforeUpdate
  58015. this.beforeUpdateParticles(start, end, update);
  58016. this._cam_axisX.x = 1.0;
  58017. this._cam_axisX.y = 0.0;
  58018. this._cam_axisX.z = 0.0;
  58019. this._cam_axisY.x = 0.0;
  58020. this._cam_axisY.y = 1.0;
  58021. this._cam_axisY.z = 0.0;
  58022. this._cam_axisZ.x = 0.0;
  58023. this._cam_axisZ.y = 0.0;
  58024. this._cam_axisZ.z = 1.0;
  58025. // cases when the World Matrix is to be computed first
  58026. if (this.billboard || this._depthSort) {
  58027. this.mesh.computeWorldMatrix(true);
  58028. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58029. }
  58030. // if the particles will always face the camera
  58031. if (this.billboard) {
  58032. // compute the camera position and un-rotate it by the current mesh rotation
  58033. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58034. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58035. this._cam_axisZ.normalize();
  58036. // same for camera up vector extracted from the cam view matrix
  58037. var view = this._camera.getViewMatrix(true);
  58038. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58039. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58040. this._cam_axisY.normalize();
  58041. this._cam_axisX.normalize();
  58042. }
  58043. // if depthSort, compute the camera global position in the mesh local system
  58044. if (this._depthSort) {
  58045. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58046. }
  58047. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58048. var idx = 0; // current position index in the global array positions32
  58049. var index = 0; // position start index in the global array positions32 of the current particle
  58050. var colidx = 0; // current color index in the global array colors32
  58051. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58052. var uvidx = 0; // current uv index in the global array uvs32
  58053. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58054. var pt = 0; // current index in the particle model shape
  58055. if (this.mesh.isFacetDataEnabled) {
  58056. this._computeBoundingBox = true;
  58057. }
  58058. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58059. if (this._computeBoundingBox) {
  58060. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58061. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58062. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58063. }
  58064. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58065. if (this.mesh._boundingInfo) {
  58066. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58067. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58068. }
  58069. }
  58070. }
  58071. // particle loop
  58072. index = this.particles[start]._pos;
  58073. var vpos = (index / 3) | 0;
  58074. colorIndex = vpos * 4;
  58075. uvIndex = vpos * 2;
  58076. for (var p = start; p <= end; p++) {
  58077. this._particle = this.particles[p];
  58078. this._shape = this._particle._model._shape;
  58079. this._shapeUV = this._particle._model._shapeUV;
  58080. // call to custom user function to update the particle properties
  58081. this.updateParticle(this._particle);
  58082. // camera-particle distance for depth sorting
  58083. if (this._depthSort && this._depthSortParticles) {
  58084. var dsp = this.depthSortedParticles[p];
  58085. dsp.ind = this._particle._ind;
  58086. dsp.indicesLength = this._particle._model._indicesLength;
  58087. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58088. }
  58089. // skip the computations for inactive or already invisible particles
  58090. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58091. // increment indexes for the next particle
  58092. pt = this._shape.length;
  58093. index += pt * 3;
  58094. colorIndex += pt * 4;
  58095. uvIndex += pt * 2;
  58096. continue;
  58097. }
  58098. if (this._particle.isVisible) {
  58099. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58100. this._particleHasParent = (this._particle.parentId !== null);
  58101. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58102. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58103. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58104. // particle rotation matrix
  58105. if (this.billboard) {
  58106. this._particle.rotation.x = 0.0;
  58107. this._particle.rotation.y = 0.0;
  58108. }
  58109. if (this._computeParticleRotation || this.billboard) {
  58110. if (this._particle.rotationQuaternion) {
  58111. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58112. }
  58113. else {
  58114. this._yaw = this._particle.rotation.y;
  58115. this._pitch = this._particle.rotation.x;
  58116. this._roll = this._particle.rotation.z;
  58117. this._quaternionRotationYPR();
  58118. }
  58119. this._quaternionToRotationMatrix();
  58120. }
  58121. if (this._particleHasParent) {
  58122. this._parent = this.particles[this._particle.parentId];
  58123. 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];
  58124. 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];
  58125. 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];
  58126. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58127. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58128. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58129. if (this._computeParticleRotation || this.billboard) {
  58130. 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];
  58131. 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];
  58132. 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];
  58133. 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];
  58134. 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];
  58135. 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];
  58136. 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];
  58137. 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];
  58138. 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];
  58139. }
  58140. }
  58141. else {
  58142. this._particle._globalPosition.x = this._particle.position.x;
  58143. this._particle._globalPosition.y = this._particle.position.y;
  58144. this._particle._globalPosition.z = this._particle.position.z;
  58145. if (this._computeParticleRotation || this.billboard) {
  58146. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58147. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58148. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58149. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58150. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58151. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58152. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58153. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58154. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58155. }
  58156. }
  58157. if (this._particle.translateFromPivot) {
  58158. this._pivotBackTranslation.x = 0.0;
  58159. this._pivotBackTranslation.y = 0.0;
  58160. this._pivotBackTranslation.z = 0.0;
  58161. }
  58162. else {
  58163. this._pivotBackTranslation.x = this._scaledPivot.x;
  58164. this._pivotBackTranslation.y = this._scaledPivot.y;
  58165. this._pivotBackTranslation.z = this._scaledPivot.z;
  58166. }
  58167. // particle vertex loop
  58168. for (pt = 0; pt < this._shape.length; pt++) {
  58169. idx = index + pt * 3;
  58170. colidx = colorIndex + pt * 4;
  58171. uvidx = uvIndex + pt * 2;
  58172. this._vertex.x = this._shape[pt].x;
  58173. this._vertex.y = this._shape[pt].y;
  58174. this._vertex.z = this._shape[pt].z;
  58175. if (this._computeParticleVertex) {
  58176. this.updateParticleVertex(this._particle, this._vertex, pt);
  58177. }
  58178. // positions
  58179. this._vertex.x *= this._particle.scaling.x;
  58180. this._vertex.y *= this._particle.scaling.y;
  58181. this._vertex.z *= this._particle.scaling.z;
  58182. this._vertex.x -= this._scaledPivot.x;
  58183. this._vertex.y -= this._scaledPivot.y;
  58184. this._vertex.z -= this._scaledPivot.z;
  58185. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58186. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58187. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58188. this._rotated.x += this._pivotBackTranslation.x;
  58189. this._rotated.y += this._pivotBackTranslation.y;
  58190. this._rotated.z += this._pivotBackTranslation.z;
  58191. 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;
  58192. 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;
  58193. 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;
  58194. if (this._computeBoundingBox) {
  58195. if (this._positions32[idx] < this._minimum.x) {
  58196. this._minimum.x = this._positions32[idx];
  58197. }
  58198. if (this._positions32[idx] > this._maximum.x) {
  58199. this._maximum.x = this._positions32[idx];
  58200. }
  58201. if (this._positions32[idx + 1] < this._minimum.y) {
  58202. this._minimum.y = this._positions32[idx + 1];
  58203. }
  58204. if (this._positions32[idx + 1] > this._maximum.y) {
  58205. this._maximum.y = this._positions32[idx + 1];
  58206. }
  58207. if (this._positions32[idx + 2] < this._minimum.z) {
  58208. this._minimum.z = this._positions32[idx + 2];
  58209. }
  58210. if (this._positions32[idx + 2] > this._maximum.z) {
  58211. this._maximum.z = this._positions32[idx + 2];
  58212. }
  58213. }
  58214. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58215. if (!this._computeParticleVertex) {
  58216. this._normal.x = this._fixedNormal32[idx];
  58217. this._normal.y = this._fixedNormal32[idx + 1];
  58218. this._normal.z = this._fixedNormal32[idx + 2];
  58219. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58220. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58221. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58222. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58223. 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;
  58224. 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;
  58225. }
  58226. if (this._computeParticleColor && this._particle.color) {
  58227. this._colors32[colidx] = this._particle.color.r;
  58228. this._colors32[colidx + 1] = this._particle.color.g;
  58229. this._colors32[colidx + 2] = this._particle.color.b;
  58230. this._colors32[colidx + 3] = this._particle.color.a;
  58231. }
  58232. if (this._computeParticleTexture) {
  58233. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58234. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58235. }
  58236. }
  58237. }
  58238. // particle just set invisible : scaled to zero and positioned at the origin
  58239. else {
  58240. this._particle._stillInvisible = true; // mark the particle as invisible
  58241. for (pt = 0; pt < this._shape.length; pt++) {
  58242. idx = index + pt * 3;
  58243. colidx = colorIndex + pt * 4;
  58244. uvidx = uvIndex + pt * 2;
  58245. this._positions32[idx] = 0.0;
  58246. this._positions32[idx + 1] = 0.0;
  58247. this._positions32[idx + 2] = 0.0;
  58248. this._normals32[idx] = 0.0;
  58249. this._normals32[idx + 1] = 0.0;
  58250. this._normals32[idx + 2] = 0.0;
  58251. if (this._computeParticleColor && this._particle.color) {
  58252. this._colors32[colidx] = this._particle.color.r;
  58253. this._colors32[colidx + 1] = this._particle.color.g;
  58254. this._colors32[colidx + 2] = this._particle.color.b;
  58255. this._colors32[colidx + 3] = this._particle.color.a;
  58256. }
  58257. if (this._computeParticleTexture) {
  58258. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58259. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58260. }
  58261. }
  58262. }
  58263. // if the particle intersections must be computed : update the bbInfo
  58264. if (this._particlesIntersect) {
  58265. var bInfo = this._particle._boundingInfo;
  58266. var bBox = bInfo.boundingBox;
  58267. var bSphere = bInfo.boundingSphere;
  58268. if (!this._bSphereOnly) {
  58269. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58270. for (var b = 0; b < bBox.vectors.length; b++) {
  58271. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58272. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58273. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58274. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58275. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58276. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58277. 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;
  58278. 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;
  58279. 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;
  58280. }
  58281. bBox._update(this.mesh._worldMatrix);
  58282. }
  58283. // place and scale the particle bouding sphere in the SPS local system, then update it
  58284. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58285. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58286. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58287. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58288. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58289. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58290. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58291. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58292. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58293. 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));
  58294. bSphere._update(this.mesh._worldMatrix);
  58295. }
  58296. // increment indexes for the next particle
  58297. index = idx + 3;
  58298. colorIndex = colidx + 4;
  58299. uvIndex = uvidx + 2;
  58300. }
  58301. // if the VBO must be updated
  58302. if (update) {
  58303. if (this._computeParticleColor) {
  58304. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58305. }
  58306. if (this._computeParticleTexture) {
  58307. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58308. }
  58309. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58310. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58311. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58312. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58313. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58314. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58315. for (var i = 0; i < this._normals32.length; i++) {
  58316. this._fixedNormal32[i] = this._normals32[i];
  58317. }
  58318. }
  58319. if (!this.mesh.areNormalsFrozen) {
  58320. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58321. }
  58322. }
  58323. if (this._depthSort && this._depthSortParticles) {
  58324. this.depthSortedParticles.sort(this._depthSortFunction);
  58325. var dspl = this.depthSortedParticles.length;
  58326. var sorted = 0;
  58327. var lind = 0;
  58328. var sind = 0;
  58329. var sid = 0;
  58330. for (sorted = 0; sorted < dspl; sorted++) {
  58331. lind = this.depthSortedParticles[sorted].indicesLength;
  58332. sind = this.depthSortedParticles[sorted].ind;
  58333. for (var i = 0; i < lind; i++) {
  58334. this._indices32[sid] = this._indices[sind + i];
  58335. sid++;
  58336. }
  58337. }
  58338. this.mesh.updateIndices(this._indices32);
  58339. }
  58340. }
  58341. if (this._computeBoundingBox) {
  58342. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58343. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58344. }
  58345. this.afterUpdateParticles(start, end, update);
  58346. return this;
  58347. };
  58348. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58349. this._halfroll = this._roll * 0.5;
  58350. this._halfpitch = this._pitch * 0.5;
  58351. this._halfyaw = this._yaw * 0.5;
  58352. this._sinRoll = Math.sin(this._halfroll);
  58353. this._cosRoll = Math.cos(this._halfroll);
  58354. this._sinPitch = Math.sin(this._halfpitch);
  58355. this._cosPitch = Math.cos(this._halfpitch);
  58356. this._sinYaw = Math.sin(this._halfyaw);
  58357. this._cosYaw = Math.cos(this._halfyaw);
  58358. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58359. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58360. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58361. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58362. };
  58363. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58364. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58365. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58366. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58367. this._rotMatrix.m[3] = 0;
  58368. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58369. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58370. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58371. this._rotMatrix.m[7] = 0;
  58372. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58373. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58374. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58375. this._rotMatrix.m[11] = 0;
  58376. this._rotMatrix.m[12] = 0;
  58377. this._rotMatrix.m[13] = 0;
  58378. this._rotMatrix.m[14] = 0;
  58379. this._rotMatrix.m[15] = 1.0;
  58380. };
  58381. /**
  58382. * Disposes the SPS.
  58383. */
  58384. SolidParticleSystem.prototype.dispose = function () {
  58385. this.mesh.dispose();
  58386. this.vars = null;
  58387. // drop references to internal big arrays for the GC
  58388. this._positions = null;
  58389. this._indices = null;
  58390. this._normals = null;
  58391. this._uvs = null;
  58392. this._colors = null;
  58393. this._indices32 = null;
  58394. this._positions32 = null;
  58395. this._normals32 = null;
  58396. this._fixedNormal32 = null;
  58397. this._uvs32 = null;
  58398. this._colors32 = null;
  58399. this.pickedParticles = null;
  58400. };
  58401. /**
  58402. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58403. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58404. * @returns the SPS.
  58405. */
  58406. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58407. if (!this._isVisibilityBoxLocked) {
  58408. this.mesh.refreshBoundingInfo();
  58409. }
  58410. return this;
  58411. };
  58412. /**
  58413. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58414. * @param size the size (float) of the visibility box
  58415. * note : this doesn't lock the SPS mesh bounding box.
  58416. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58417. */
  58418. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58419. var vis = size / 2;
  58420. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58421. };
  58422. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58423. /**
  58424. * Gets whether the SPS as always visible or not
  58425. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58426. */
  58427. get: function () {
  58428. return this._alwaysVisible;
  58429. },
  58430. /**
  58431. * Sets the SPS as always visible or not
  58432. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58433. */
  58434. set: function (val) {
  58435. this._alwaysVisible = val;
  58436. this.mesh.alwaysSelectAsActiveMesh = val;
  58437. },
  58438. enumerable: true,
  58439. configurable: true
  58440. });
  58441. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58442. /**
  58443. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58444. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58445. */
  58446. get: function () {
  58447. return this._isVisibilityBoxLocked;
  58448. },
  58449. /**
  58450. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58452. */
  58453. set: function (val) {
  58454. this._isVisibilityBoxLocked = val;
  58455. var boundingInfo = this.mesh.getBoundingInfo();
  58456. boundingInfo.isLocked = val;
  58457. },
  58458. enumerable: true,
  58459. configurable: true
  58460. });
  58461. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58462. /**
  58463. * Gets if `setParticles()` computes the particle rotations or not.
  58464. * Default value : true. The SPS is faster when it's set to false.
  58465. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58466. */
  58467. get: function () {
  58468. return this._computeParticleRotation;
  58469. },
  58470. /**
  58471. * Tells to `setParticles()` to compute the particle rotations or not.
  58472. * Default value : true. The SPS is faster when it's set to false.
  58473. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58474. */
  58475. set: function (val) {
  58476. this._computeParticleRotation = val;
  58477. },
  58478. enumerable: true,
  58479. configurable: true
  58480. });
  58481. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58482. /**
  58483. * Gets if `setParticles()` computes the particle colors or not.
  58484. * Default value : true. The SPS is faster when it's set to false.
  58485. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58486. */
  58487. get: function () {
  58488. return this._computeParticleColor;
  58489. },
  58490. /**
  58491. * Tells to `setParticles()` to compute the particle colors or not.
  58492. * Default value : true. The SPS is faster when it's set to false.
  58493. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58494. */
  58495. set: function (val) {
  58496. this._computeParticleColor = val;
  58497. },
  58498. enumerable: true,
  58499. configurable: true
  58500. });
  58501. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58502. /**
  58503. * Gets if `setParticles()` computes the particle textures or not.
  58504. * Default value : true. The SPS is faster when it's set to false.
  58505. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58506. */
  58507. get: function () {
  58508. return this._computeParticleTexture;
  58509. },
  58510. set: function (val) {
  58511. this._computeParticleTexture = val;
  58512. },
  58513. enumerable: true,
  58514. configurable: true
  58515. });
  58516. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58517. /**
  58518. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58519. * Default value : false. The SPS is faster when it's set to false.
  58520. * Note : the particle custom vertex positions aren't stored values.
  58521. */
  58522. get: function () {
  58523. return this._computeParticleVertex;
  58524. },
  58525. /**
  58526. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58527. * Default value : false. The SPS is faster when it's set to false.
  58528. * Note : the particle custom vertex positions aren't stored values.
  58529. */
  58530. set: function (val) {
  58531. this._computeParticleVertex = val;
  58532. },
  58533. enumerable: true,
  58534. configurable: true
  58535. });
  58536. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58537. /**
  58538. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58539. */
  58540. get: function () {
  58541. return this._computeBoundingBox;
  58542. },
  58543. /**
  58544. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58545. */
  58546. set: function (val) {
  58547. this._computeBoundingBox = val;
  58548. },
  58549. enumerable: true,
  58550. configurable: true
  58551. });
  58552. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58553. /**
  58554. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58555. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58556. * Default : `true`
  58557. */
  58558. get: function () {
  58559. return this._depthSortParticles;
  58560. },
  58561. /**
  58562. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58563. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58564. * Default : `true`
  58565. */
  58566. set: function (val) {
  58567. this._depthSortParticles = val;
  58568. },
  58569. enumerable: true,
  58570. configurable: true
  58571. });
  58572. // =======================================================================
  58573. // Particle behavior logic
  58574. // these following methods may be overwritten by the user to fit his needs
  58575. /**
  58576. * This function does nothing. It may be overwritten to set all the particle first values.
  58577. * The SPS doesn't call this function, you may have to call it by your own.
  58578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58579. */
  58580. SolidParticleSystem.prototype.initParticles = function () {
  58581. };
  58582. /**
  58583. * This function does nothing. It may be overwritten to recycle a particle.
  58584. * The SPS doesn't call this function, you may have to call it by your own.
  58585. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58586. * @param particle The particle to recycle
  58587. * @returns the recycled particle
  58588. */
  58589. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58590. return particle;
  58591. };
  58592. /**
  58593. * Updates a particle : this function should be overwritten by the user.
  58594. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58595. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58596. * @example : just set a particle position or velocity and recycle conditions
  58597. * @param particle The particle to update
  58598. * @returns the updated particle
  58599. */
  58600. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58601. return particle;
  58602. };
  58603. /**
  58604. * Updates a vertex of a particle : it can be overwritten by the user.
  58605. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58606. * @param particle the current particle
  58607. * @param vertex the current index of the current particle
  58608. * @param pt the index of the current vertex in the particle shape
  58609. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58610. * @example : just set a vertex particle position
  58611. * @returns the updated vertex
  58612. */
  58613. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58614. return vertex;
  58615. };
  58616. /**
  58617. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58618. * This does nothing and may be overwritten by the user.
  58619. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58620. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58621. * @param update the boolean update value actually passed to setParticles()
  58622. */
  58623. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58624. };
  58625. /**
  58626. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58627. * This will be passed three parameters.
  58628. * This does nothing and may be overwritten by the user.
  58629. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58630. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58631. * @param update the boolean update value actually passed to setParticles()
  58632. */
  58633. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58634. };
  58635. return SolidParticleSystem;
  58636. }());
  58637. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58638. })(BABYLON || (BABYLON = {}));
  58639. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58640. var BABYLON;
  58641. (function (BABYLON) {
  58642. var ShaderMaterial = /** @class */ (function (_super) {
  58643. __extends(ShaderMaterial, _super);
  58644. function ShaderMaterial(name, scene, shaderPath, options) {
  58645. var _this = _super.call(this, name, scene) || this;
  58646. _this._textures = {};
  58647. _this._textureArrays = {};
  58648. _this._floats = {};
  58649. _this._ints = {};
  58650. _this._floatsArrays = {};
  58651. _this._colors3 = {};
  58652. _this._colors3Arrays = {};
  58653. _this._colors4 = {};
  58654. _this._vectors2 = {};
  58655. _this._vectors3 = {};
  58656. _this._vectors4 = {};
  58657. _this._matrices = {};
  58658. _this._matrices3x3 = {};
  58659. _this._matrices2x2 = {};
  58660. _this._vectors2Arrays = {};
  58661. _this._vectors3Arrays = {};
  58662. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58663. _this._shaderPath = shaderPath;
  58664. options.needAlphaBlending = options.needAlphaBlending || false;
  58665. options.needAlphaTesting = options.needAlphaTesting || false;
  58666. options.attributes = options.attributes || ["position", "normal", "uv"];
  58667. options.uniforms = options.uniforms || ["worldViewProjection"];
  58668. options.uniformBuffers = options.uniformBuffers || [];
  58669. options.samplers = options.samplers || [];
  58670. options.defines = options.defines || [];
  58671. _this._options = options;
  58672. return _this;
  58673. }
  58674. ShaderMaterial.prototype.getClassName = function () {
  58675. return "ShaderMaterial";
  58676. };
  58677. ShaderMaterial.prototype.needAlphaBlending = function () {
  58678. return this._options.needAlphaBlending;
  58679. };
  58680. ShaderMaterial.prototype.needAlphaTesting = function () {
  58681. return this._options.needAlphaTesting;
  58682. };
  58683. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58684. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58685. this._options.uniforms.push(uniformName);
  58686. }
  58687. };
  58688. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58689. if (this._options.samplers.indexOf(name) === -1) {
  58690. this._options.samplers.push(name);
  58691. }
  58692. this._textures[name] = texture;
  58693. return this;
  58694. };
  58695. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58696. if (this._options.samplers.indexOf(name) === -1) {
  58697. this._options.samplers.push(name);
  58698. }
  58699. this._checkUniform(name);
  58700. this._textureArrays[name] = textures;
  58701. return this;
  58702. };
  58703. ShaderMaterial.prototype.setFloat = function (name, value) {
  58704. this._checkUniform(name);
  58705. this._floats[name] = value;
  58706. return this;
  58707. };
  58708. ShaderMaterial.prototype.setInt = function (name, value) {
  58709. this._checkUniform(name);
  58710. this._ints[name] = value;
  58711. return this;
  58712. };
  58713. ShaderMaterial.prototype.setFloats = function (name, value) {
  58714. this._checkUniform(name);
  58715. this._floatsArrays[name] = value;
  58716. return this;
  58717. };
  58718. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58719. this._checkUniform(name);
  58720. this._colors3[name] = value;
  58721. return this;
  58722. };
  58723. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58724. this._checkUniform(name);
  58725. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58726. color.toArray(arr, arr.length);
  58727. return arr;
  58728. }, []);
  58729. return this;
  58730. };
  58731. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58732. this._checkUniform(name);
  58733. this._colors4[name] = value;
  58734. return this;
  58735. };
  58736. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58737. this._checkUniform(name);
  58738. this._vectors2[name] = value;
  58739. return this;
  58740. };
  58741. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58742. this._checkUniform(name);
  58743. this._vectors3[name] = value;
  58744. return this;
  58745. };
  58746. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58747. this._checkUniform(name);
  58748. this._vectors4[name] = value;
  58749. return this;
  58750. };
  58751. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58752. this._checkUniform(name);
  58753. this._matrices[name] = value;
  58754. return this;
  58755. };
  58756. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58757. this._checkUniform(name);
  58758. this._matrices3x3[name] = value;
  58759. return this;
  58760. };
  58761. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58762. this._checkUniform(name);
  58763. this._matrices2x2[name] = value;
  58764. return this;
  58765. };
  58766. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58767. this._checkUniform(name);
  58768. this._vectors2Arrays[name] = value;
  58769. return this;
  58770. };
  58771. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58772. this._checkUniform(name);
  58773. this._vectors3Arrays[name] = value;
  58774. return this;
  58775. };
  58776. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58777. if (!mesh) {
  58778. return true;
  58779. }
  58780. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58781. return false;
  58782. }
  58783. return false;
  58784. };
  58785. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58786. var scene = this.getScene();
  58787. var engine = scene.getEngine();
  58788. if (!this.checkReadyOnEveryCall) {
  58789. if (this._renderId === scene.getRenderId()) {
  58790. if (this._checkCache(scene, mesh, useInstances)) {
  58791. return true;
  58792. }
  58793. }
  58794. }
  58795. // Instances
  58796. var defines = [];
  58797. var attribs = [];
  58798. var fallbacks = new BABYLON.EffectFallbacks();
  58799. if (useInstances) {
  58800. defines.push("#define INSTANCES");
  58801. }
  58802. for (var index = 0; index < this._options.defines.length; index++) {
  58803. defines.push(this._options.defines[index]);
  58804. }
  58805. for (var index = 0; index < this._options.attributes.length; index++) {
  58806. attribs.push(this._options.attributes[index]);
  58807. }
  58808. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58809. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58810. defines.push("#define VERTEXCOLOR");
  58811. }
  58812. // Bones
  58813. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58814. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58815. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58816. if (mesh.numBoneInfluencers > 4) {
  58817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58819. }
  58820. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58821. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58822. fallbacks.addCPUSkinningFallback(0, mesh);
  58823. if (this._options.uniforms.indexOf("mBones") === -1) {
  58824. this._options.uniforms.push("mBones");
  58825. }
  58826. }
  58827. else {
  58828. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58829. }
  58830. // Textures
  58831. for (var name in this._textures) {
  58832. if (!this._textures[name].isReady()) {
  58833. return false;
  58834. }
  58835. }
  58836. // Alpha test
  58837. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58838. defines.push("#define ALPHATEST");
  58839. }
  58840. var previousEffect = this._effect;
  58841. var join = defines.join("\n");
  58842. this._effect = engine.createEffect(this._shaderPath, {
  58843. attributes: attribs,
  58844. uniformsNames: this._options.uniforms,
  58845. uniformBuffersNames: this._options.uniformBuffers,
  58846. samplers: this._options.samplers,
  58847. defines: join,
  58848. fallbacks: fallbacks,
  58849. onCompiled: this.onCompiled,
  58850. onError: this.onError
  58851. }, engine);
  58852. if (!this._effect.isReady()) {
  58853. return false;
  58854. }
  58855. if (previousEffect !== this._effect) {
  58856. scene.resetCachedMaterial();
  58857. }
  58858. this._renderId = scene.getRenderId();
  58859. return true;
  58860. };
  58861. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58862. var scene = this.getScene();
  58863. if (!this._effect) {
  58864. return;
  58865. }
  58866. if (this._options.uniforms.indexOf("world") !== -1) {
  58867. this._effect.setMatrix("world", world);
  58868. }
  58869. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58870. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58871. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58872. }
  58873. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58874. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58875. }
  58876. };
  58877. ShaderMaterial.prototype.bind = function (world, mesh) {
  58878. // Std values
  58879. this.bindOnlyWorldMatrix(world);
  58880. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58881. if (this._options.uniforms.indexOf("view") !== -1) {
  58882. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58883. }
  58884. if (this._options.uniforms.indexOf("projection") !== -1) {
  58885. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58886. }
  58887. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58888. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58889. }
  58890. // Bones
  58891. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58892. var name;
  58893. // Texture
  58894. for (name in this._textures) {
  58895. this._effect.setTexture(name, this._textures[name]);
  58896. }
  58897. // Texture arrays
  58898. for (name in this._textureArrays) {
  58899. this._effect.setTextureArray(name, this._textureArrays[name]);
  58900. }
  58901. // Int
  58902. for (name in this._ints) {
  58903. this._effect.setInt(name, this._ints[name]);
  58904. }
  58905. // Float
  58906. for (name in this._floats) {
  58907. this._effect.setFloat(name, this._floats[name]);
  58908. }
  58909. // Floats
  58910. for (name in this._floatsArrays) {
  58911. this._effect.setArray(name, this._floatsArrays[name]);
  58912. }
  58913. // Color3
  58914. for (name in this._colors3) {
  58915. this._effect.setColor3(name, this._colors3[name]);
  58916. }
  58917. for (name in this._colors3Arrays) {
  58918. this._effect.setArray3(name, this._colors3Arrays[name]);
  58919. }
  58920. // Color4
  58921. for (name in this._colors4) {
  58922. var color = this._colors4[name];
  58923. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58924. }
  58925. // Vector2
  58926. for (name in this._vectors2) {
  58927. this._effect.setVector2(name, this._vectors2[name]);
  58928. }
  58929. // Vector3
  58930. for (name in this._vectors3) {
  58931. this._effect.setVector3(name, this._vectors3[name]);
  58932. }
  58933. // Vector4
  58934. for (name in this._vectors4) {
  58935. this._effect.setVector4(name, this._vectors4[name]);
  58936. }
  58937. // Matrix
  58938. for (name in this._matrices) {
  58939. this._effect.setMatrix(name, this._matrices[name]);
  58940. }
  58941. // Matrix 3x3
  58942. for (name in this._matrices3x3) {
  58943. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58944. }
  58945. // Matrix 2x2
  58946. for (name in this._matrices2x2) {
  58947. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58948. }
  58949. // Vector2Array
  58950. for (name in this._vectors2Arrays) {
  58951. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58952. }
  58953. // Vector3Array
  58954. for (name in this._vectors3Arrays) {
  58955. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58956. }
  58957. }
  58958. this._afterBind(mesh);
  58959. };
  58960. ShaderMaterial.prototype.getActiveTextures = function () {
  58961. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58962. for (var name in this._textures) {
  58963. activeTextures.push(this._textures[name]);
  58964. }
  58965. for (var name in this._textureArrays) {
  58966. var array = this._textureArrays[name];
  58967. for (var index = 0; index < array.length; index++) {
  58968. activeTextures.push(array[index]);
  58969. }
  58970. }
  58971. return activeTextures;
  58972. };
  58973. ShaderMaterial.prototype.hasTexture = function (texture) {
  58974. if (_super.prototype.hasTexture.call(this, texture)) {
  58975. return true;
  58976. }
  58977. for (var name in this._textures) {
  58978. if (this._textures[name] === texture) {
  58979. return true;
  58980. }
  58981. }
  58982. for (var name in this._textureArrays) {
  58983. var array = this._textureArrays[name];
  58984. for (var index = 0; index < array.length; index++) {
  58985. if (array[index] === texture) {
  58986. return true;
  58987. }
  58988. }
  58989. }
  58990. return false;
  58991. };
  58992. ShaderMaterial.prototype.clone = function (name) {
  58993. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58994. return newShaderMaterial;
  58995. };
  58996. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58997. if (forceDisposeTextures) {
  58998. var name;
  58999. for (name in this._textures) {
  59000. this._textures[name].dispose();
  59001. }
  59002. for (name in this._textureArrays) {
  59003. var array = this._textureArrays[name];
  59004. for (var index = 0; index < array.length; index++) {
  59005. array[index].dispose();
  59006. }
  59007. }
  59008. }
  59009. this._textures = {};
  59010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59011. };
  59012. ShaderMaterial.prototype.serialize = function () {
  59013. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59014. serializationObject.customType = "BABYLON.ShaderMaterial";
  59015. serializationObject.options = this._options;
  59016. serializationObject.shaderPath = this._shaderPath;
  59017. var name;
  59018. // Texture
  59019. serializationObject.textures = {};
  59020. for (name in this._textures) {
  59021. serializationObject.textures[name] = this._textures[name].serialize();
  59022. }
  59023. // Texture arrays
  59024. serializationObject.textureArrays = {};
  59025. for (name in this._textureArrays) {
  59026. serializationObject.textureArrays[name] = [];
  59027. var array = this._textureArrays[name];
  59028. for (var index = 0; index < array.length; index++) {
  59029. serializationObject.textureArrays[name].push(array[index].serialize());
  59030. }
  59031. }
  59032. // Float
  59033. serializationObject.floats = {};
  59034. for (name in this._floats) {
  59035. serializationObject.floats[name] = this._floats[name];
  59036. }
  59037. // Float s
  59038. serializationObject.FloatArrays = {};
  59039. for (name in this._floatsArrays) {
  59040. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59041. }
  59042. // Color3
  59043. serializationObject.colors3 = {};
  59044. for (name in this._colors3) {
  59045. serializationObject.colors3[name] = this._colors3[name].asArray();
  59046. }
  59047. // Color3 array
  59048. serializationObject.colors3Arrays = {};
  59049. for (name in this._colors3Arrays) {
  59050. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59051. }
  59052. // Color4
  59053. serializationObject.colors4 = {};
  59054. for (name in this._colors4) {
  59055. serializationObject.colors4[name] = this._colors4[name].asArray();
  59056. }
  59057. // Vector2
  59058. serializationObject.vectors2 = {};
  59059. for (name in this._vectors2) {
  59060. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59061. }
  59062. // Vector3
  59063. serializationObject.vectors3 = {};
  59064. for (name in this._vectors3) {
  59065. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59066. }
  59067. // Vector4
  59068. serializationObject.vectors4 = {};
  59069. for (name in this._vectors4) {
  59070. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59071. }
  59072. // Matrix
  59073. serializationObject.matrices = {};
  59074. for (name in this._matrices) {
  59075. serializationObject.matrices[name] = this._matrices[name].asArray();
  59076. }
  59077. // Matrix 3x3
  59078. serializationObject.matrices3x3 = {};
  59079. for (name in this._matrices3x3) {
  59080. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59081. }
  59082. // Matrix 2x2
  59083. serializationObject.matrices2x2 = {};
  59084. for (name in this._matrices2x2) {
  59085. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59086. }
  59087. // Vector2Array
  59088. serializationObject.vectors2Arrays = {};
  59089. for (name in this._vectors2Arrays) {
  59090. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59091. }
  59092. // Vector3Array
  59093. serializationObject.vectors3Arrays = {};
  59094. for (name in this._vectors3Arrays) {
  59095. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59096. }
  59097. return serializationObject;
  59098. };
  59099. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59100. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59101. var name;
  59102. // Texture
  59103. for (name in source.textures) {
  59104. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59105. }
  59106. // Texture arrays
  59107. for (name in source.textureArrays) {
  59108. var array = source.textureArrays[name];
  59109. var textureArray = new Array();
  59110. for (var index = 0; index < array.length; index++) {
  59111. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59112. }
  59113. material.setTextureArray(name, textureArray);
  59114. }
  59115. // Float
  59116. for (name in source.floats) {
  59117. material.setFloat(name, source.floats[name]);
  59118. }
  59119. // Float s
  59120. for (name in source.floatsArrays) {
  59121. material.setFloats(name, source.floatsArrays[name]);
  59122. }
  59123. // Color3
  59124. for (name in source.colors3) {
  59125. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59126. }
  59127. // Color3 arrays
  59128. for (name in source.colors3Arrays) {
  59129. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59130. if (i % 3 === 0) {
  59131. arr.push([num]);
  59132. }
  59133. else {
  59134. arr[arr.length - 1].push(num);
  59135. }
  59136. return arr;
  59137. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59138. material.setColor3Array(name, colors);
  59139. }
  59140. // Color4
  59141. for (name in source.colors4) {
  59142. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59143. }
  59144. // Vector2
  59145. for (name in source.vectors2) {
  59146. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59147. }
  59148. // Vector3
  59149. for (name in source.vectors3) {
  59150. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59151. }
  59152. // Vector4
  59153. for (name in source.vectors4) {
  59154. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59155. }
  59156. // Matrix
  59157. for (name in source.matrices) {
  59158. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59159. }
  59160. // Matrix 3x3
  59161. for (name in source.matrices3x3) {
  59162. material.setMatrix3x3(name, source.matrices3x3[name]);
  59163. }
  59164. // Matrix 2x2
  59165. for (name in source.matrices2x2) {
  59166. material.setMatrix2x2(name, source.matrices2x2[name]);
  59167. }
  59168. // Vector2Array
  59169. for (name in source.vectors2Arrays) {
  59170. material.setArray2(name, source.vectors2Arrays[name]);
  59171. }
  59172. // Vector3Array
  59173. for (name in source.vectors3Arrays) {
  59174. material.setArray3(name, source.vectors3Arrays[name]);
  59175. }
  59176. return material;
  59177. };
  59178. return ShaderMaterial;
  59179. }(BABYLON.Material));
  59180. BABYLON.ShaderMaterial = ShaderMaterial;
  59181. })(BABYLON || (BABYLON = {}));
  59182. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59183. var BABYLON;
  59184. (function (BABYLON) {
  59185. var GroundMesh = /** @class */ (function (_super) {
  59186. __extends(GroundMesh, _super);
  59187. function GroundMesh(name, scene) {
  59188. var _this = _super.call(this, name, scene) || this;
  59189. _this.generateOctree = false;
  59190. return _this;
  59191. }
  59192. GroundMesh.prototype.getClassName = function () {
  59193. return "GroundMesh";
  59194. };
  59195. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59196. get: function () {
  59197. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59198. },
  59199. enumerable: true,
  59200. configurable: true
  59201. });
  59202. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59203. get: function () {
  59204. return this._subdivisionsX;
  59205. },
  59206. enumerable: true,
  59207. configurable: true
  59208. });
  59209. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59210. get: function () {
  59211. return this._subdivisionsY;
  59212. },
  59213. enumerable: true,
  59214. configurable: true
  59215. });
  59216. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59217. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59218. this._subdivisionsX = chunksCount;
  59219. this._subdivisionsY = chunksCount;
  59220. this.subdivide(chunksCount);
  59221. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59222. };
  59223. /**
  59224. * Returns a height (y) value in the Worl system :
  59225. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59226. * Returns the ground y position if (x, z) are outside the ground surface.
  59227. */
  59228. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59229. var world = this.getWorldMatrix();
  59230. var invMat = BABYLON.Tmp.Matrix[5];
  59231. world.invertToRef(invMat);
  59232. var tmpVect = BABYLON.Tmp.Vector3[8];
  59233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59234. x = tmpVect.x;
  59235. z = tmpVect.z;
  59236. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59237. return this.position.y;
  59238. }
  59239. if (!this._heightQuads || this._heightQuads.length == 0) {
  59240. this._initHeightQuads();
  59241. this._computeHeightQuads();
  59242. }
  59243. var facet = this._getFacetAt(x, z);
  59244. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59245. // return y in the World system
  59246. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59247. return tmpVect.y;
  59248. };
  59249. /**
  59250. * Returns a normalized vector (Vector3) orthogonal to the ground
  59251. * at the ground coordinates (x, z) expressed in the World system.
  59252. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59253. */
  59254. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59255. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59256. this.getNormalAtCoordinatesToRef(x, z, normal);
  59257. return normal;
  59258. };
  59259. /**
  59260. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59261. * at the ground coordinates (x, z) expressed in the World system.
  59262. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59263. * Returns the GroundMesh.
  59264. */
  59265. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59266. var world = this.getWorldMatrix();
  59267. var tmpMat = BABYLON.Tmp.Matrix[5];
  59268. world.invertToRef(tmpMat);
  59269. var tmpVect = BABYLON.Tmp.Vector3[8];
  59270. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59271. x = tmpVect.x;
  59272. z = tmpVect.z;
  59273. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59274. return this;
  59275. }
  59276. if (!this._heightQuads || this._heightQuads.length == 0) {
  59277. this._initHeightQuads();
  59278. this._computeHeightQuads();
  59279. }
  59280. var facet = this._getFacetAt(x, z);
  59281. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59282. return this;
  59283. };
  59284. /**
  59285. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59286. * if the ground has been updated.
  59287. * This can be used in the render loop.
  59288. * Returns the GroundMesh.
  59289. */
  59290. GroundMesh.prototype.updateCoordinateHeights = function () {
  59291. if (!this._heightQuads || this._heightQuads.length == 0) {
  59292. this._initHeightQuads();
  59293. }
  59294. this._computeHeightQuads();
  59295. return this;
  59296. };
  59297. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59298. GroundMesh.prototype._getFacetAt = function (x, z) {
  59299. // retrieve col and row from x, z coordinates in the ground local system
  59300. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59301. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59302. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59303. var facet;
  59304. if (z < quad.slope.x * x + quad.slope.y) {
  59305. facet = quad.facet1;
  59306. }
  59307. else {
  59308. facet = quad.facet2;
  59309. }
  59310. return facet;
  59311. };
  59312. // Creates and populates the heightMap array with "facet" elements :
  59313. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59314. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59315. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59316. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59317. // Returns the GroundMesh.
  59318. GroundMesh.prototype._initHeightQuads = function () {
  59319. var subdivisionsX = this._subdivisionsX;
  59320. var subdivisionsY = this._subdivisionsY;
  59321. this._heightQuads = new Array();
  59322. for (var row = 0; row < subdivisionsY; row++) {
  59323. for (var col = 0; col < subdivisionsX; col++) {
  59324. 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) };
  59325. this._heightQuads[row * subdivisionsX + col] = quad;
  59326. }
  59327. }
  59328. return this;
  59329. };
  59330. // Compute each quad element values and update the the heightMap array :
  59331. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59332. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59333. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59334. // Returns the GroundMesh.
  59335. GroundMesh.prototype._computeHeightQuads = function () {
  59336. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59337. if (!positions) {
  59338. return this;
  59339. }
  59340. var v1 = BABYLON.Tmp.Vector3[3];
  59341. var v2 = BABYLON.Tmp.Vector3[2];
  59342. var v3 = BABYLON.Tmp.Vector3[1];
  59343. var v4 = BABYLON.Tmp.Vector3[0];
  59344. var v1v2 = BABYLON.Tmp.Vector3[4];
  59345. var v1v3 = BABYLON.Tmp.Vector3[5];
  59346. var v1v4 = BABYLON.Tmp.Vector3[6];
  59347. var norm1 = BABYLON.Tmp.Vector3[7];
  59348. var norm2 = BABYLON.Tmp.Vector3[8];
  59349. var i = 0;
  59350. var j = 0;
  59351. var k = 0;
  59352. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59353. var h = 0;
  59354. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59355. var d2 = 0;
  59356. var subdivisionsX = this._subdivisionsX;
  59357. var subdivisionsY = this._subdivisionsY;
  59358. for (var row = 0; row < subdivisionsY; row++) {
  59359. for (var col = 0; col < subdivisionsX; col++) {
  59360. i = col * 3;
  59361. j = row * (subdivisionsX + 1) * 3;
  59362. k = (row + 1) * (subdivisionsX + 1) * 3;
  59363. v1.x = positions[j + i];
  59364. v1.y = positions[j + i + 1];
  59365. v1.z = positions[j + i + 2];
  59366. v2.x = positions[j + i + 3];
  59367. v2.y = positions[j + i + 4];
  59368. v2.z = positions[j + i + 5];
  59369. v3.x = positions[k + i];
  59370. v3.y = positions[k + i + 1];
  59371. v3.z = positions[k + i + 2];
  59372. v4.x = positions[k + i + 3];
  59373. v4.y = positions[k + i + 4];
  59374. v4.z = positions[k + i + 5];
  59375. // 2D slope V1V4
  59376. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59377. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59378. // facet equations :
  59379. // we compute each facet normal vector
  59380. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59381. // we compute the value d by applying the equation to v1 which belongs to the plane
  59382. // then we store the facet equation in a Vector4
  59383. v2.subtractToRef(v1, v1v2);
  59384. v3.subtractToRef(v1, v1v3);
  59385. v4.subtractToRef(v1, v1v4);
  59386. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59387. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59388. norm1.normalize();
  59389. norm2.normalize();
  59390. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59391. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59392. var quad = this._heightQuads[row * subdivisionsX + col];
  59393. quad.slope.copyFromFloats(cd, h);
  59394. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59395. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59396. }
  59397. }
  59398. return this;
  59399. };
  59400. GroundMesh.prototype.serialize = function (serializationObject) {
  59401. _super.prototype.serialize.call(this, serializationObject);
  59402. serializationObject.subdivisionsX = this._subdivisionsX;
  59403. serializationObject.subdivisionsY = this._subdivisionsY;
  59404. serializationObject.minX = this._minX;
  59405. serializationObject.maxX = this._maxX;
  59406. serializationObject.minZ = this._minZ;
  59407. serializationObject.maxZ = this._maxZ;
  59408. serializationObject.width = this._width;
  59409. serializationObject.height = this._height;
  59410. };
  59411. GroundMesh.Parse = function (parsedMesh, scene) {
  59412. var result = new GroundMesh(parsedMesh.name, scene);
  59413. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59414. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59415. result._minX = parsedMesh.minX;
  59416. result._maxX = parsedMesh.maxX;
  59417. result._minZ = parsedMesh.minZ;
  59418. result._maxZ = parsedMesh.maxZ;
  59419. result._width = parsedMesh.width;
  59420. result._height = parsedMesh.height;
  59421. return result;
  59422. };
  59423. return GroundMesh;
  59424. }(BABYLON.Mesh));
  59425. BABYLON.GroundMesh = GroundMesh;
  59426. })(BABYLON || (BABYLON = {}));
  59427. //# sourceMappingURL=babylon.groundMesh.js.map
  59428. var BABYLON;
  59429. (function (BABYLON) {
  59430. /**
  59431. * Creates an instance based on a source mesh.
  59432. */
  59433. var InstancedMesh = /** @class */ (function (_super) {
  59434. __extends(InstancedMesh, _super);
  59435. function InstancedMesh(name, source) {
  59436. var _this = _super.call(this, name, source.getScene()) || this;
  59437. source.instances.push(_this);
  59438. _this._sourceMesh = source;
  59439. _this.position.copyFrom(source.position);
  59440. _this.rotation.copyFrom(source.rotation);
  59441. _this.scaling.copyFrom(source.scaling);
  59442. if (source.rotationQuaternion) {
  59443. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59444. }
  59445. _this.infiniteDistance = source.infiniteDistance;
  59446. _this.setPivotMatrix(source.getPivotMatrix());
  59447. _this.refreshBoundingInfo();
  59448. _this._syncSubMeshes();
  59449. return _this;
  59450. }
  59451. /**
  59452. * Returns the string "InstancedMesh".
  59453. */
  59454. InstancedMesh.prototype.getClassName = function () {
  59455. return "InstancedMesh";
  59456. };
  59457. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59458. // Methods
  59459. get: function () {
  59460. return this._sourceMesh.receiveShadows;
  59461. },
  59462. enumerable: true,
  59463. configurable: true
  59464. });
  59465. Object.defineProperty(InstancedMesh.prototype, "material", {
  59466. get: function () {
  59467. return this._sourceMesh.material;
  59468. },
  59469. enumerable: true,
  59470. configurable: true
  59471. });
  59472. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59473. get: function () {
  59474. return this._sourceMesh.visibility;
  59475. },
  59476. enumerable: true,
  59477. configurable: true
  59478. });
  59479. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59480. get: function () {
  59481. return this._sourceMesh.skeleton;
  59482. },
  59483. enumerable: true,
  59484. configurable: true
  59485. });
  59486. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59487. get: function () {
  59488. return this._sourceMesh.renderingGroupId;
  59489. },
  59490. set: function (value) {
  59491. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59492. return;
  59493. }
  59494. //no-op with warning
  59495. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59496. },
  59497. enumerable: true,
  59498. configurable: true
  59499. });
  59500. /**
  59501. * Returns the total number of vertices (integer).
  59502. */
  59503. InstancedMesh.prototype.getTotalVertices = function () {
  59504. return this._sourceMesh.getTotalVertices();
  59505. };
  59506. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59507. get: function () {
  59508. return this._sourceMesh;
  59509. },
  59510. enumerable: true,
  59511. configurable: true
  59512. });
  59513. /**
  59514. * Is this node ready to be used/rendered
  59515. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59516. * @return {boolean} is it ready
  59517. */
  59518. InstancedMesh.prototype.isReady = function (completeCheck) {
  59519. if (completeCheck === void 0) { completeCheck = false; }
  59520. return this._sourceMesh.isReady(completeCheck, true);
  59521. };
  59522. /**
  59523. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59524. */
  59525. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59526. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59527. };
  59528. /**
  59529. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59530. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59531. * The `data` are either a numeric array either a Float32Array.
  59532. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59533. * 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).
  59534. * Note that a new underlying VertexBuffer object is created each call.
  59535. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59536. *
  59537. * Possible `kind` values :
  59538. * - BABYLON.VertexBuffer.PositionKind
  59539. * - BABYLON.VertexBuffer.UVKind
  59540. * - BABYLON.VertexBuffer.UV2Kind
  59541. * - BABYLON.VertexBuffer.UV3Kind
  59542. * - BABYLON.VertexBuffer.UV4Kind
  59543. * - BABYLON.VertexBuffer.UV5Kind
  59544. * - BABYLON.VertexBuffer.UV6Kind
  59545. * - BABYLON.VertexBuffer.ColorKind
  59546. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59547. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59548. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59549. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59550. *
  59551. * Returns the Mesh.
  59552. */
  59553. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59554. if (this.sourceMesh) {
  59555. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59556. }
  59557. return this.sourceMesh;
  59558. };
  59559. /**
  59560. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59561. * If the mesh has no geometry, it is simply returned as it is.
  59562. * The `data` are either a numeric array either a Float32Array.
  59563. * No new underlying VertexBuffer object is created.
  59564. * 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.
  59565. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59566. *
  59567. * Possible `kind` values :
  59568. * - BABYLON.VertexBuffer.PositionKind
  59569. * - BABYLON.VertexBuffer.UVKind
  59570. * - BABYLON.VertexBuffer.UV2Kind
  59571. * - BABYLON.VertexBuffer.UV3Kind
  59572. * - BABYLON.VertexBuffer.UV4Kind
  59573. * - BABYLON.VertexBuffer.UV5Kind
  59574. * - BABYLON.VertexBuffer.UV6Kind
  59575. * - BABYLON.VertexBuffer.ColorKind
  59576. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59577. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59578. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59579. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59580. *
  59581. * Returns the Mesh.
  59582. */
  59583. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59584. if (this.sourceMesh) {
  59585. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59586. }
  59587. return this.sourceMesh;
  59588. };
  59589. /**
  59590. * Sets the mesh indices.
  59591. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59592. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59593. * This method creates a new index buffer each call.
  59594. * Returns the Mesh.
  59595. */
  59596. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59597. if (totalVertices === void 0) { totalVertices = null; }
  59598. if (this.sourceMesh) {
  59599. this.sourceMesh.setIndices(indices, totalVertices);
  59600. }
  59601. return this.sourceMesh;
  59602. };
  59603. /**
  59604. * Boolean : True if the mesh owns the requested kind of data.
  59605. */
  59606. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59607. return this._sourceMesh.isVerticesDataPresent(kind);
  59608. };
  59609. /**
  59610. * Returns an array of indices (IndicesArray).
  59611. */
  59612. InstancedMesh.prototype.getIndices = function () {
  59613. return this._sourceMesh.getIndices();
  59614. };
  59615. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59616. get: function () {
  59617. return this._sourceMesh._positions;
  59618. },
  59619. enumerable: true,
  59620. configurable: true
  59621. });
  59622. /**
  59623. * Sets a new updated BoundingInfo to the mesh.
  59624. * Returns the mesh.
  59625. */
  59626. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59627. var meshBB = this._sourceMesh.getBoundingInfo();
  59628. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59629. this._updateBoundingInfo();
  59630. return this;
  59631. };
  59632. InstancedMesh.prototype._preActivate = function () {
  59633. if (this._currentLOD) {
  59634. this._currentLOD._preActivate();
  59635. }
  59636. return this;
  59637. };
  59638. InstancedMesh.prototype._activate = function (renderId) {
  59639. if (this._currentLOD) {
  59640. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59641. }
  59642. return this;
  59643. };
  59644. /**
  59645. * Returns the current associated LOD AbstractMesh.
  59646. */
  59647. InstancedMesh.prototype.getLOD = function (camera) {
  59648. if (!camera) {
  59649. return this;
  59650. }
  59651. var boundingInfo = this.getBoundingInfo();
  59652. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59653. if (this._currentLOD === this.sourceMesh) {
  59654. return this;
  59655. }
  59656. return this._currentLOD;
  59657. };
  59658. InstancedMesh.prototype._syncSubMeshes = function () {
  59659. this.releaseSubMeshes();
  59660. if (this._sourceMesh.subMeshes) {
  59661. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59662. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59663. }
  59664. }
  59665. return this;
  59666. };
  59667. InstancedMesh.prototype._generatePointsArray = function () {
  59668. return this._sourceMesh._generatePointsArray();
  59669. };
  59670. /**
  59671. * Creates a new InstancedMesh from the current mesh.
  59672. * - name (string) : the cloned mesh name
  59673. * - newParent (optional Node) : the optional Node to parent the clone to.
  59674. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59675. *
  59676. * Returns the clone.
  59677. */
  59678. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59679. var result = this._sourceMesh.createInstance(name);
  59680. // Deep copy
  59681. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59682. // Bounding info
  59683. this.refreshBoundingInfo();
  59684. // Parent
  59685. if (newParent) {
  59686. result.parent = newParent;
  59687. }
  59688. if (!doNotCloneChildren) {
  59689. // Children
  59690. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59691. var mesh = this.getScene().meshes[index];
  59692. if (mesh.parent === this) {
  59693. mesh.clone(mesh.name, result);
  59694. }
  59695. }
  59696. }
  59697. result.computeWorldMatrix(true);
  59698. return result;
  59699. };
  59700. /**
  59701. * Disposes the InstancedMesh.
  59702. * Returns nothing.
  59703. */
  59704. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59705. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59706. // Remove from mesh
  59707. var index = this._sourceMesh.instances.indexOf(this);
  59708. this._sourceMesh.instances.splice(index, 1);
  59709. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59710. };
  59711. return InstancedMesh;
  59712. }(BABYLON.AbstractMesh));
  59713. BABYLON.InstancedMesh = InstancedMesh;
  59714. })(BABYLON || (BABYLON = {}));
  59715. //# sourceMappingURL=babylon.instancedMesh.js.map
  59716. var BABYLON;
  59717. (function (BABYLON) {
  59718. var LinesMesh = /** @class */ (function (_super) {
  59719. __extends(LinesMesh, _super);
  59720. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59721. if (scene === void 0) { scene = null; }
  59722. if (parent === void 0) { parent = null; }
  59723. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59724. _this.useVertexColor = useVertexColor;
  59725. _this.useVertexAlpha = useVertexAlpha;
  59726. _this.color = new BABYLON.Color3(1, 1, 1);
  59727. _this.alpha = 1;
  59728. if (source) {
  59729. _this.color = source.color.clone();
  59730. _this.alpha = source.alpha;
  59731. _this.useVertexColor = source.useVertexColor;
  59732. _this.useVertexAlpha = source.useVertexAlpha;
  59733. }
  59734. _this._intersectionThreshold = 0.1;
  59735. var defines = [];
  59736. var options = {
  59737. attributes: [BABYLON.VertexBuffer.PositionKind],
  59738. uniforms: ["world", "viewProjection"],
  59739. needAlphaBlending: true,
  59740. defines: defines
  59741. };
  59742. if (useVertexAlpha === false) {
  59743. options.needAlphaBlending = false;
  59744. }
  59745. if (!useVertexColor) {
  59746. options.uniforms.push("color");
  59747. }
  59748. else {
  59749. options.defines.push("#define VERTEXCOLOR");
  59750. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59751. }
  59752. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59753. return _this;
  59754. }
  59755. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59756. /**
  59757. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59758. * This margin is expressed in world space coordinates, so its value may vary.
  59759. * Default value is 0.1
  59760. * @returns the intersection Threshold value.
  59761. */
  59762. get: function () {
  59763. return this._intersectionThreshold;
  59764. },
  59765. /**
  59766. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59767. * This margin is expressed in world space coordinates, so its value may vary.
  59768. * @param value the new threshold to apply
  59769. */
  59770. set: function (value) {
  59771. if (this._intersectionThreshold === value) {
  59772. return;
  59773. }
  59774. this._intersectionThreshold = value;
  59775. if (this.geometry) {
  59776. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59777. }
  59778. },
  59779. enumerable: true,
  59780. configurable: true
  59781. });
  59782. /**
  59783. * Returns the string "LineMesh"
  59784. */
  59785. LinesMesh.prototype.getClassName = function () {
  59786. return "LinesMesh";
  59787. };
  59788. Object.defineProperty(LinesMesh.prototype, "material", {
  59789. get: function () {
  59790. return this._colorShader;
  59791. },
  59792. set: function (value) {
  59793. // Do nothing
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59799. get: function () {
  59800. return false;
  59801. },
  59802. enumerable: true,
  59803. configurable: true
  59804. });
  59805. LinesMesh.prototype.createInstance = function (name) {
  59806. throw new Error("LinesMeshes do not support createInstance.");
  59807. };
  59808. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59809. if (!this._geometry) {
  59810. return this;
  59811. }
  59812. // VBOs
  59813. this._geometry._bind(this._colorShader.getEffect());
  59814. // Color
  59815. if (!this.useVertexColor) {
  59816. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59817. }
  59818. return this;
  59819. };
  59820. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59821. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59822. return this;
  59823. }
  59824. var engine = this.getScene().getEngine();
  59825. // Draw order
  59826. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59827. return this;
  59828. };
  59829. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59830. this._colorShader.dispose();
  59831. _super.prototype.dispose.call(this, doNotRecurse);
  59832. };
  59833. /**
  59834. * Returns a new LineMesh object cloned from the current one.
  59835. */
  59836. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59837. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59838. };
  59839. return LinesMesh;
  59840. }(BABYLON.Mesh));
  59841. BABYLON.LinesMesh = LinesMesh;
  59842. })(BABYLON || (BABYLON = {}));
  59843. //# sourceMappingURL=babylon.linesMesh.js.map
  59844. var BABYLON;
  59845. (function (BABYLON) {
  59846. /**
  59847. * Class containing static functions to help procedurally build meshes
  59848. */
  59849. var MeshBuilder = /** @class */ (function () {
  59850. function MeshBuilder() {
  59851. }
  59852. MeshBuilder.updateSideOrientation = function (orientation) {
  59853. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59854. return BABYLON.Mesh.DOUBLESIDE;
  59855. }
  59856. if (orientation === undefined || orientation === null) {
  59857. return BABYLON.Mesh.FRONTSIDE;
  59858. }
  59859. return orientation;
  59860. };
  59861. /**
  59862. * Creates a box mesh
  59863. * * The parameter `size` sets the size (float) of each box side (default 1)
  59864. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59865. * * 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)
  59866. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59867. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59868. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59870. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59871. * @param name defines the name of the mesh
  59872. * @param options defines the options used to create the mesh
  59873. * @param scene defines the hosting scene
  59874. * @returns the box mesh
  59875. */
  59876. MeshBuilder.CreateBox = function (name, options, scene) {
  59877. if (scene === void 0) { scene = null; }
  59878. var box = new BABYLON.Mesh(name, scene);
  59879. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59880. box._originalBuilderSideOrientation = options.sideOrientation;
  59881. var vertexData = BABYLON.VertexData.CreateBox(options);
  59882. vertexData.applyToMesh(box, options.updatable);
  59883. return box;
  59884. };
  59885. /**
  59886. * Creates a sphere mesh
  59887. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59888. * * 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`)
  59889. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59890. * * 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
  59891. * * 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)
  59892. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59893. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59895. * @param name defines the name of the mesh
  59896. * @param options defines the options used to create the mesh
  59897. * @param scene defines the hosting scene
  59898. * @returns the sphere mesh
  59899. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59900. */
  59901. MeshBuilder.CreateSphere = function (name, options, scene) {
  59902. var sphere = new BABYLON.Mesh(name, scene);
  59903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59904. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59905. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59906. vertexData.applyToMesh(sphere, options.updatable);
  59907. return sphere;
  59908. };
  59909. /**
  59910. * Creates a plane polygonal mesh. By default, this is a disc
  59911. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59912. * * 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
  59913. * * 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
  59914. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59915. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59916. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59917. * @param name defines the name of the mesh
  59918. * @param options defines the options used to create the mesh
  59919. * @param scene defines the hosting scene
  59920. * @returns the plane polygonal mesh
  59921. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59922. */
  59923. MeshBuilder.CreateDisc = function (name, options, scene) {
  59924. if (scene === void 0) { scene = null; }
  59925. var disc = new BABYLON.Mesh(name, scene);
  59926. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59927. disc._originalBuilderSideOrientation = options.sideOrientation;
  59928. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59929. vertexData.applyToMesh(disc, options.updatable);
  59930. return disc;
  59931. };
  59932. /**
  59933. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59934. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59935. * * 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`)
  59936. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59937. * * 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
  59938. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59939. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59941. * @param name defines the name of the mesh
  59942. * @param options defines the options used to create the mesh
  59943. * @param scene defines the hosting scene
  59944. * @returns the icosahedron mesh
  59945. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59946. */
  59947. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59948. var sphere = new BABYLON.Mesh(name, scene);
  59949. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59950. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59951. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59952. vertexData.applyToMesh(sphere, options.updatable);
  59953. return sphere;
  59954. };
  59955. ;
  59956. /**
  59957. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59958. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59959. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59960. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59961. * * 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
  59962. * * 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
  59963. * * 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
  59964. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59965. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59966. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59967. * * 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
  59968. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59969. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  59970. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59971. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59972. * @param name defines the name of the mesh
  59973. * @param options defines the options used to create the mesh
  59974. * @param scene defines the hosting scene
  59975. * @returns the ribbon mesh
  59976. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59977. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59978. */
  59979. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59980. if (scene === void 0) { scene = null; }
  59981. var pathArray = options.pathArray;
  59982. var closeArray = options.closeArray;
  59983. var closePath = options.closePath;
  59984. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59985. var instance = options.instance;
  59986. var updatable = options.updatable;
  59987. if (instance) { // existing ribbon instance update
  59988. // positionFunction : ribbon case
  59989. // only pathArray and sideOrientation parameters are taken into account for positions update
  59990. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59991. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59992. var positionFunction = function (positions) {
  59993. var minlg = pathArray[0].length;
  59994. var i = 0;
  59995. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59996. for (var si = 1; si <= ns; si++) {
  59997. for (var p = 0; p < pathArray.length; p++) {
  59998. var path = pathArray[p];
  59999. var l = path.length;
  60000. minlg = (minlg < l) ? minlg : l;
  60001. var j = 0;
  60002. while (j < minlg) {
  60003. positions[i] = path[j].x;
  60004. positions[i + 1] = path[j].y;
  60005. positions[i + 2] = path[j].z;
  60006. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60007. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60008. }
  60009. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60010. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60011. }
  60012. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60013. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60014. }
  60015. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60016. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60017. }
  60018. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60019. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60020. }
  60021. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60022. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60023. }
  60024. j++;
  60025. i += 3;
  60026. }
  60027. if (instance._closePath) {
  60028. positions[i] = path[0].x;
  60029. positions[i + 1] = path[0].y;
  60030. positions[i + 2] = path[0].z;
  60031. i += 3;
  60032. }
  60033. }
  60034. }
  60035. };
  60036. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60037. positionFunction(positions);
  60038. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60039. instance._boundingInfo.update(instance._worldMatrix);
  60040. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60041. if (options.colors) {
  60042. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60043. for (var c = 0; c < options.colors.length; c++) {
  60044. colors[c * 4] = options.colors[c].r;
  60045. colors[c * 4 + 1] = options.colors[c].g;
  60046. colors[c * 4 + 2] = options.colors[c].b;
  60047. colors[c * 4 + 3] = options.colors[c].a;
  60048. }
  60049. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60050. }
  60051. if (options.uvs) {
  60052. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60053. for (var i = 0; i < options.uvs.length; i++) {
  60054. uvs[i * 2] = options.uvs[i].x;
  60055. uvs[i * 2 + 1] = options.uvs[i].y;
  60056. }
  60057. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60058. }
  60059. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60060. var indices = instance.getIndices();
  60061. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60062. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60063. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60064. if (instance._closePath) {
  60065. var indexFirst = 0;
  60066. var indexLast = 0;
  60067. for (var p = 0; p < pathArray.length; p++) {
  60068. indexFirst = instance._idx[p] * 3;
  60069. if (p + 1 < pathArray.length) {
  60070. indexLast = (instance._idx[p + 1] - 1) * 3;
  60071. }
  60072. else {
  60073. indexLast = normals.length - 3;
  60074. }
  60075. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60076. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60077. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60078. normals[indexLast] = normals[indexFirst];
  60079. normals[indexLast + 1] = normals[indexFirst + 1];
  60080. normals[indexLast + 2] = normals[indexFirst + 2];
  60081. }
  60082. }
  60083. if (!(instance.areNormalsFrozen)) {
  60084. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60085. }
  60086. }
  60087. return instance;
  60088. }
  60089. else { // new ribbon creation
  60090. var ribbon = new BABYLON.Mesh(name, scene);
  60091. ribbon._originalBuilderSideOrientation = sideOrientation;
  60092. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60093. if (closePath) {
  60094. ribbon._idx = vertexData._idx;
  60095. }
  60096. ribbon._closePath = closePath;
  60097. ribbon._closeArray = closeArray;
  60098. vertexData.applyToMesh(ribbon, updatable);
  60099. return ribbon;
  60100. }
  60101. };
  60102. /**
  60103. * Creates a cylinder or a cone mesh
  60104. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60105. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60106. * * 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.
  60107. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60108. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60109. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60110. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60111. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60112. * * 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).
  60113. * * 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
  60114. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60115. * * 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
  60116. * * 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.
  60117. * * If `enclose` is false, a ring surface is one element.
  60118. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60119. * * 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
  60120. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60121. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60122. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60123. * @param name defines the name of the mesh
  60124. * @param options defines the options used to create the mesh
  60125. * @param scene defines the hosting scene
  60126. * @returns the cylinder mesh
  60127. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60128. */
  60129. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60130. var cylinder = new BABYLON.Mesh(name, scene);
  60131. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60132. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60133. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60134. vertexData.applyToMesh(cylinder, options.updatable);
  60135. return cylinder;
  60136. };
  60137. /**
  60138. * Creates a torus mesh
  60139. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60140. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60141. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60142. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60143. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60144. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60145. * @param name defines the name of the mesh
  60146. * @param options defines the options used to create the mesh
  60147. * @param scene defines the hosting scene
  60148. * @returns the torus mesh
  60149. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60150. */
  60151. MeshBuilder.CreateTorus = function (name, options, scene) {
  60152. var torus = new BABYLON.Mesh(name, scene);
  60153. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60154. torus._originalBuilderSideOrientation = options.sideOrientation;
  60155. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60156. vertexData.applyToMesh(torus, options.updatable);
  60157. return torus;
  60158. };
  60159. /**
  60160. * Creates a torus knot mesh
  60161. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60162. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60163. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60164. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60165. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60166. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60167. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60168. * @param name defines the name of the mesh
  60169. * @param options defines the options used to create the mesh
  60170. * @param scene defines the hosting scene
  60171. * @returns the torus knot mesh
  60172. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60173. */
  60174. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60175. var torusKnot = new BABYLON.Mesh(name, scene);
  60176. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60177. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60178. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60179. vertexData.applyToMesh(torusKnot, options.updatable);
  60180. return torusKnot;
  60181. };
  60182. /**
  60183. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60184. * * 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
  60185. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60186. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60187. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60188. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60189. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60190. * * 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
  60191. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60193. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60194. * @param name defines the name of the new line system
  60195. * @param options defines the options used to create the line system
  60196. * @param scene defines the hosting scene
  60197. * @returns a new line system mesh
  60198. */
  60199. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60200. var instance = options.instance;
  60201. var lines = options.lines;
  60202. var colors = options.colors;
  60203. if (instance) { // lines update
  60204. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60205. var vertexColor;
  60206. var lineColors;
  60207. if (colors) {
  60208. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60209. }
  60210. var i = 0;
  60211. var c = 0;
  60212. for (var l = 0; l < lines.length; l++) {
  60213. var points = lines[l];
  60214. for (var p = 0; p < points.length; p++) {
  60215. positions[i] = points[p].x;
  60216. positions[i + 1] = points[p].y;
  60217. positions[i + 2] = points[p].z;
  60218. if (colors && vertexColor) {
  60219. lineColors = colors[l];
  60220. vertexColor[c] = lineColors[p].r;
  60221. vertexColor[c + 1] = lineColors[p].g;
  60222. vertexColor[c + 2] = lineColors[p].b;
  60223. vertexColor[c + 3] = lineColors[p].a;
  60224. c += 4;
  60225. }
  60226. i += 3;
  60227. }
  60228. }
  60229. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60230. if (colors && vertexColor) {
  60231. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60232. }
  60233. return instance;
  60234. }
  60235. // line system creation
  60236. var useVertexColor = (colors) ? true : false;
  60237. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60238. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60239. vertexData.applyToMesh(lineSystem, options.updatable);
  60240. return lineSystem;
  60241. };
  60242. /**
  60243. * Creates a line mesh
  60244. * 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
  60245. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60246. * * The parameter `points` is an array successive Vector3
  60247. * * 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
  60248. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60249. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60250. * * When updating an instance, remember that only point positions can change, not the number of points
  60251. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60252. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60253. * @param name defines the name of the new line system
  60254. * @param options defines the options used to create the line system
  60255. * @param scene defines the hosting scene
  60256. * @returns a new line mesh
  60257. */
  60258. MeshBuilder.CreateLines = function (name, options, scene) {
  60259. if (scene === void 0) { scene = null; }
  60260. var colors = (options.colors) ? [options.colors] : null;
  60261. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60262. return lines;
  60263. };
  60264. /**
  60265. * Creates a dashed line mesh
  60266. * * 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
  60267. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60268. * * The parameter `points` is an array successive Vector3
  60269. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60270. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60271. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60272. * * 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
  60273. * * When updating an instance, remember that only point positions can change, not the number of points
  60274. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60275. * @param name defines the name of the mesh
  60276. * @param options defines the options used to create the mesh
  60277. * @param scene defines the hosting scene
  60278. * @returns the dashed line mesh
  60279. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60280. */
  60281. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60282. if (scene === void 0) { scene = null; }
  60283. var points = options.points;
  60284. var instance = options.instance;
  60285. var gapSize = options.gapSize || 1;
  60286. var dashSize = options.dashSize || 3;
  60287. if (instance) { // dashed lines update
  60288. var positionFunction = function (positions) {
  60289. var curvect = BABYLON.Vector3.Zero();
  60290. var nbSeg = positions.length / 6;
  60291. var lg = 0;
  60292. var nb = 0;
  60293. var shft = 0;
  60294. var dashshft = 0;
  60295. var curshft = 0;
  60296. var p = 0;
  60297. var i = 0;
  60298. var j = 0;
  60299. for (i = 0; i < points.length - 1; i++) {
  60300. points[i + 1].subtractToRef(points[i], curvect);
  60301. lg += curvect.length();
  60302. }
  60303. shft = lg / nbSeg;
  60304. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60305. for (i = 0; i < points.length - 1; i++) {
  60306. points[i + 1].subtractToRef(points[i], curvect);
  60307. nb = Math.floor(curvect.length() / shft);
  60308. curvect.normalize();
  60309. j = 0;
  60310. while (j < nb && p < positions.length) {
  60311. curshft = shft * j;
  60312. positions[p] = points[i].x + curshft * curvect.x;
  60313. positions[p + 1] = points[i].y + curshft * curvect.y;
  60314. positions[p + 2] = points[i].z + curshft * curvect.z;
  60315. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60316. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60317. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60318. p += 6;
  60319. j++;
  60320. }
  60321. }
  60322. while (p < positions.length) {
  60323. positions[p] = points[i].x;
  60324. positions[p + 1] = points[i].y;
  60325. positions[p + 2] = points[i].z;
  60326. p += 3;
  60327. }
  60328. };
  60329. instance.updateMeshPositions(positionFunction, false);
  60330. return instance;
  60331. }
  60332. // dashed lines creation
  60333. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60334. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60335. vertexData.applyToMesh(dashedLines, options.updatable);
  60336. dashedLines.dashSize = dashSize;
  60337. dashedLines.gapSize = gapSize;
  60338. return dashedLines;
  60339. };
  60340. /**
  60341. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60342. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60343. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60344. * * 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.
  60345. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60346. * * 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
  60347. * * 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
  60348. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60349. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60350. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60351. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60352. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60353. * @param name defines the name of the mesh
  60354. * @param options defines the options used to create the mesh
  60355. * @param scene defines the hosting scene
  60356. * @returns the extruded shape mesh
  60357. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60358. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60359. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60360. */
  60361. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60362. if (scene === void 0) { scene = null; }
  60363. var path = options.path;
  60364. var shape = options.shape;
  60365. var scale = options.scale || 1;
  60366. var rotation = options.rotation || 0;
  60367. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60368. var updatable = options.updatable;
  60369. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60370. var instance = options.instance || null;
  60371. var invertUV = options.invertUV || false;
  60372. 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);
  60373. };
  60374. /**
  60375. * Creates an custom extruded shape mesh.
  60376. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60377. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60378. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60379. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60380. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60381. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60382. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60383. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60384. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60385. * * 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
  60386. * * 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
  60387. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60388. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60389. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60390. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60391. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60392. * @param name defines the name of the mesh
  60393. * @param options defines the options used to create the mesh
  60394. * @param scene defines the hosting scene
  60395. * @returns the custom extruded shape mesh
  60396. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60397. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60398. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60399. */
  60400. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60401. var path = options.path;
  60402. var shape = options.shape;
  60403. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60404. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60405. var ribbonCloseArray = options.ribbonCloseArray || false;
  60406. var ribbonClosePath = options.ribbonClosePath || false;
  60407. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60408. var updatable = options.updatable;
  60409. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60410. var instance = options.instance;
  60411. var invertUV = options.invertUV || false;
  60412. 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);
  60413. };
  60414. /**
  60415. * Creates lathe mesh.
  60416. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60417. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60418. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60419. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60420. * * 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
  60421. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60422. * * 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
  60423. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60424. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60425. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60426. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60427. * @param name defines the name of the mesh
  60428. * @param options defines the options used to create the mesh
  60429. * @param scene defines the hosting scene
  60430. * @returns the lathe mesh
  60431. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60432. */
  60433. MeshBuilder.CreateLathe = function (name, options, scene) {
  60434. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60435. var closed = (options.closed === undefined) ? true : options.closed;
  60436. var shape = options.shape;
  60437. var radius = options.radius || 1;
  60438. var tessellation = options.tessellation || 64;
  60439. var updatable = options.updatable;
  60440. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60441. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60442. var pi2 = Math.PI * 2;
  60443. var paths = new Array();
  60444. var invertUV = options.invertUV || false;
  60445. var i = 0;
  60446. var p = 0;
  60447. var step = pi2 / tessellation * arc;
  60448. var rotated;
  60449. var path = new Array();
  60450. ;
  60451. for (i = 0; i <= tessellation; i++) {
  60452. var path = [];
  60453. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60454. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60455. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60456. }
  60457. for (p = 0; p < shape.length; p++) {
  60458. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60459. path.push(rotated);
  60460. }
  60461. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60462. 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));
  60463. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60464. }
  60465. paths.push(path);
  60466. }
  60467. // lathe ribbon
  60468. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60469. return lathe;
  60470. };
  60471. /**
  60472. * Creates a plane mesh
  60473. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60474. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60475. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60477. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60478. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60479. * @param name defines the name of the mesh
  60480. * @param options defines the options used to create the mesh
  60481. * @param scene defines the hosting scene
  60482. * @returns the plane mesh
  60483. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60484. */
  60485. MeshBuilder.CreatePlane = function (name, options, scene) {
  60486. var plane = new BABYLON.Mesh(name, scene);
  60487. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60488. plane._originalBuilderSideOrientation = options.sideOrientation;
  60489. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60490. vertexData.applyToMesh(plane, options.updatable);
  60491. if (options.sourcePlane) {
  60492. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60493. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60494. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60495. plane.rotate(vectorProduct, product);
  60496. }
  60497. return plane;
  60498. };
  60499. /**
  60500. * Creates a ground mesh
  60501. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60502. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60503. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60504. * @param name defines the name of the mesh
  60505. * @param options defines the options used to create the mesh
  60506. * @param scene defines the hosting scene
  60507. * @returns the ground mesh
  60508. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60509. */
  60510. MeshBuilder.CreateGround = function (name, options, scene) {
  60511. var ground = new BABYLON.GroundMesh(name, scene);
  60512. ground._setReady(false);
  60513. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60514. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60515. ground._width = options.width || 1;
  60516. ground._height = options.height || 1;
  60517. ground._maxX = ground._width / 2;
  60518. ground._maxZ = ground._height / 2;
  60519. ground._minX = -ground._maxX;
  60520. ground._minZ = -ground._maxZ;
  60521. var vertexData = BABYLON.VertexData.CreateGround(options);
  60522. vertexData.applyToMesh(ground, options.updatable);
  60523. ground._setReady(true);
  60524. return ground;
  60525. };
  60526. /**
  60527. * Creates a tiled ground mesh
  60528. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60529. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60530. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  60531. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  60532. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60533. * @param name defines the name of the mesh
  60534. * @param options defines the options used to create the mesh
  60535. * @param scene defines the hosting scene
  60536. * @returns the tiled ground mesh
  60537. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60538. */
  60539. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60540. var tiledGround = new BABYLON.Mesh(name, scene);
  60541. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60542. vertexData.applyToMesh(tiledGround, options.updatable);
  60543. return tiledGround;
  60544. };
  60545. /**
  60546. * Creates a ground mesh from a height map
  60547. * * The parameter `url` sets the URL of the height map image resource.
  60548. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60549. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60550. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60551. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60552. * * 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.
  60553. * * 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).
  60554. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60555. * @param name defines the name of the mesh
  60556. * @param url defines the url to the height map
  60557. * @param options defines the options used to create the mesh
  60558. * @param scene defines the hosting scene
  60559. * @returns the ground mesh
  60560. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60561. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60562. */
  60563. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60564. var width = options.width || 10.0;
  60565. var height = options.height || 10.0;
  60566. var subdivisions = options.subdivisions || 1 | 0;
  60567. var minHeight = options.minHeight || 0.0;
  60568. var maxHeight = options.maxHeight || 1.0;
  60569. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60570. var updatable = options.updatable;
  60571. var onReady = options.onReady;
  60572. var ground = new BABYLON.GroundMesh(name, scene);
  60573. ground._subdivisionsX = subdivisions;
  60574. ground._subdivisionsY = subdivisions;
  60575. ground._width = width;
  60576. ground._height = height;
  60577. ground._maxX = ground._width / 2.0;
  60578. ground._maxZ = ground._height / 2.0;
  60579. ground._minX = -ground._maxX;
  60580. ground._minZ = -ground._maxZ;
  60581. ground._setReady(false);
  60582. var onload = function (img) {
  60583. // Getting height map data
  60584. var canvas = document.createElement("canvas");
  60585. var context = canvas.getContext("2d");
  60586. if (!context) {
  60587. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60588. }
  60589. if (scene.isDisposed) {
  60590. return;
  60591. }
  60592. var bufferWidth = img.width;
  60593. var bufferHeight = img.height;
  60594. canvas.width = bufferWidth;
  60595. canvas.height = bufferHeight;
  60596. context.drawImage(img, 0, 0);
  60597. // Create VertexData from map data
  60598. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60599. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60600. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60601. width: width, height: height,
  60602. subdivisions: subdivisions,
  60603. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60604. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60605. });
  60606. vertexData.applyToMesh(ground, updatable);
  60607. //execute ready callback, if set
  60608. if (onReady) {
  60609. onReady(ground);
  60610. }
  60611. ground._setReady(true);
  60612. };
  60613. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60614. return ground;
  60615. };
  60616. /**
  60617. * Creates a polygon mesh
  60618. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60619. * * 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
  60620. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60621. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60622. * * 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)
  60623. * * Remember you can only change the shape positions, not their number when updating a polygon
  60624. * @param name defines the name of the mesh
  60625. * @param options defines the options used to create the mesh
  60626. * @param scene defines the hosting scene
  60627. * @returns the polygon mesh
  60628. */
  60629. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60631. var shape = options.shape;
  60632. var holes = options.holes || [];
  60633. var depth = options.depth || 0;
  60634. var contours = [];
  60635. var hole = [];
  60636. for (var i = 0; i < shape.length; i++) {
  60637. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60638. }
  60639. var epsilon = 0.00000001;
  60640. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60641. contours.pop();
  60642. }
  60643. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60644. for (var hNb = 0; hNb < holes.length; hNb++) {
  60645. hole = [];
  60646. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60647. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60648. }
  60649. polygonTriangulation.addHole(hole);
  60650. }
  60651. var polygon = polygonTriangulation.build(options.updatable, depth);
  60652. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60653. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60654. vertexData.applyToMesh(polygon, options.updatable);
  60655. return polygon;
  60656. };
  60657. ;
  60658. /**
  60659. * Creates an extruded polygon mesh, with depth in the Y direction.
  60660. * * 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)
  60661. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60662. * @param name defines the name of the mesh
  60663. * @param options defines the options used to create the mesh
  60664. * @param scene defines the hosting scene
  60665. * @returns the polygon mesh
  60666. */
  60667. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60668. return MeshBuilder.CreatePolygon(name, options, scene);
  60669. };
  60670. ;
  60671. /**
  60672. * Creates a tube mesh.
  60673. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60674. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60675. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60676. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60677. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60678. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  60679. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60680. * * 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
  60681. * * 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
  60682. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60683. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60684. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60685. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60686. * @param name defines the name of the mesh
  60687. * @param options defines the options used to create the mesh
  60688. * @param scene defines the hosting scene
  60689. * @returns the tube mesh
  60690. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60691. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60692. */
  60693. MeshBuilder.CreateTube = function (name, options, scene) {
  60694. var path = options.path;
  60695. var instance = options.instance;
  60696. var radius = 1.0;
  60697. if (instance) {
  60698. radius = instance.radius;
  60699. }
  60700. if (options.radius !== undefined) {
  60701. radius = options.radius;
  60702. }
  60703. ;
  60704. var tessellation = options.tessellation || 64 | 0;
  60705. var radiusFunction = options.radiusFunction || null;
  60706. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60707. var invertUV = options.invertUV || false;
  60708. var updatable = options.updatable;
  60709. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60710. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60711. // tube geometry
  60712. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60713. var tangents = path3D.getTangents();
  60714. var normals = path3D.getNormals();
  60715. var distances = path3D.getDistances();
  60716. var pi2 = Math.PI * 2;
  60717. var step = pi2 / tessellation * arc;
  60718. var returnRadius = function () { return radius; };
  60719. var radiusFunctionFinal = radiusFunction || returnRadius;
  60720. var circlePath;
  60721. var rad;
  60722. var normal;
  60723. var rotated;
  60724. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60725. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60726. for (var i = 0; i < path.length; i++) {
  60727. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60728. circlePath = Array(); // current circle array
  60729. normal = normals[i]; // current normal
  60730. for (var t = 0; t < tessellation; t++) {
  60731. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60732. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60733. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60734. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60735. circlePath[t] = rotated;
  60736. }
  60737. circlePaths[index] = circlePath;
  60738. index++;
  60739. }
  60740. // cap
  60741. var capPath = function (nbPoints, pathIndex) {
  60742. var pointCap = Array();
  60743. for (var i = 0; i < nbPoints; i++) {
  60744. pointCap.push(path[pathIndex]);
  60745. }
  60746. return pointCap;
  60747. };
  60748. switch (cap) {
  60749. case BABYLON.Mesh.NO_CAP:
  60750. break;
  60751. case BABYLON.Mesh.CAP_START:
  60752. circlePaths[0] = capPath(tessellation, 0);
  60753. circlePaths[1] = circlePaths[2].slice(0);
  60754. break;
  60755. case BABYLON.Mesh.CAP_END:
  60756. circlePaths[index] = circlePaths[index - 1].slice(0);
  60757. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60758. break;
  60759. case BABYLON.Mesh.CAP_ALL:
  60760. circlePaths[0] = capPath(tessellation, 0);
  60761. circlePaths[1] = circlePaths[2].slice(0);
  60762. circlePaths[index] = circlePaths[index - 1].slice(0);
  60763. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60764. break;
  60765. default:
  60766. break;
  60767. }
  60768. return circlePaths;
  60769. };
  60770. var path3D;
  60771. var pathArray;
  60772. if (instance) { // tube update
  60773. var arc = options.arc || instance.arc;
  60774. path3D = (instance.path3D).update(path);
  60775. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60776. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60777. instance.path3D = path3D;
  60778. instance.pathArray = pathArray;
  60779. instance.arc = arc;
  60780. instance.radius = radius;
  60781. return instance;
  60782. }
  60783. // tube creation
  60784. path3D = new BABYLON.Path3D(path);
  60785. var newPathArray = new Array();
  60786. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60787. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60788. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60789. tube.pathArray = pathArray;
  60790. tube.path3D = path3D;
  60791. tube.tessellation = tessellation;
  60792. tube.cap = cap;
  60793. tube.arc = options.arc;
  60794. tube.radius = radius;
  60795. return tube;
  60796. };
  60797. /**
  60798. * Creates a polyhedron mesh
  60799. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  60800. * * The parameter `size` (positive float, default 1) sets the polygon size
  60801. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60802. * * 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`
  60803. * * 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
  60804. * * 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)`)
  60805. * * 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
  60806. * * 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
  60807. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60808. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60809. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60810. * @param name defines the name of the mesh
  60811. * @param options defines the options used to create the mesh
  60812. * @param scene defines the hosting scene
  60813. * @returns the polyhedron mesh
  60814. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60815. */
  60816. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60817. var polyhedron = new BABYLON.Mesh(name, scene);
  60818. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60819. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60820. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60821. vertexData.applyToMesh(polyhedron, options.updatable);
  60822. return polyhedron;
  60823. };
  60824. /**
  60825. * Creates a decal mesh.
  60826. * 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
  60827. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60828. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60829. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60830. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60831. * @param name defines the name of the mesh
  60832. * @param sourceMesh defines the mesh where the decal must be applied
  60833. * @param options defines the options used to create the mesh
  60834. * @param scene defines the hosting scene
  60835. * @returns the decal mesh
  60836. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60837. */
  60838. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60839. var indices = sourceMesh.getIndices();
  60840. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60841. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60842. var position = options.position || BABYLON.Vector3.Zero();
  60843. var normal = options.normal || BABYLON.Vector3.Up();
  60844. var size = options.size || BABYLON.Vector3.One();
  60845. var angle = options.angle || 0;
  60846. // Getting correct rotation
  60847. if (!normal) {
  60848. var target = new BABYLON.Vector3(0, 0, 1);
  60849. var camera = sourceMesh.getScene().activeCamera;
  60850. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60851. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60852. }
  60853. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60854. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60855. var pitch = Math.atan2(normal.y, len);
  60856. // Matrix
  60857. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60858. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60859. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60860. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60861. var vertexData = new BABYLON.VertexData();
  60862. vertexData.indices = [];
  60863. vertexData.positions = [];
  60864. vertexData.normals = [];
  60865. vertexData.uvs = [];
  60866. var currentVertexDataIndex = 0;
  60867. var extractDecalVector3 = function (indexId) {
  60868. var result = new BABYLON.PositionNormalVertex();
  60869. if (!indices || !positions || !normals) {
  60870. return result;
  60871. }
  60872. var vertexId = indices[indexId];
  60873. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60874. // Send vector to decal local world
  60875. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60876. // Get normal
  60877. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60878. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60879. return result;
  60880. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60881. var clip = function (vertices, axis) {
  60882. if (vertices.length === 0) {
  60883. return vertices;
  60884. }
  60885. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60886. var clipVertices = function (v0, v1) {
  60887. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60888. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60889. };
  60890. var result = new Array();
  60891. for (var index = 0; index < vertices.length; index += 3) {
  60892. var v1Out;
  60893. var v2Out;
  60894. var v3Out;
  60895. var total = 0;
  60896. var nV1 = null;
  60897. var nV2 = null;
  60898. var nV3 = null;
  60899. var nV4 = null;
  60900. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60901. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60902. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60903. v1Out = d1 > 0;
  60904. v2Out = d2 > 0;
  60905. v3Out = d3 > 0;
  60906. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60907. switch (total) {
  60908. case 0:
  60909. result.push(vertices[index]);
  60910. result.push(vertices[index + 1]);
  60911. result.push(vertices[index + 2]);
  60912. break;
  60913. case 1:
  60914. if (v1Out) {
  60915. nV1 = vertices[index + 1];
  60916. nV2 = vertices[index + 2];
  60917. nV3 = clipVertices(vertices[index], nV1);
  60918. nV4 = clipVertices(vertices[index], nV2);
  60919. }
  60920. if (v2Out) {
  60921. nV1 = vertices[index];
  60922. nV2 = vertices[index + 2];
  60923. nV3 = clipVertices(vertices[index + 1], nV1);
  60924. nV4 = clipVertices(vertices[index + 1], nV2);
  60925. result.push(nV3);
  60926. result.push(nV2.clone());
  60927. result.push(nV1.clone());
  60928. result.push(nV2.clone());
  60929. result.push(nV3.clone());
  60930. result.push(nV4);
  60931. break;
  60932. }
  60933. if (v3Out) {
  60934. nV1 = vertices[index];
  60935. nV2 = vertices[index + 1];
  60936. nV3 = clipVertices(vertices[index + 2], nV1);
  60937. nV4 = clipVertices(vertices[index + 2], nV2);
  60938. }
  60939. if (nV1 && nV2 && nV3 && nV4) {
  60940. result.push(nV1.clone());
  60941. result.push(nV2.clone());
  60942. result.push(nV3);
  60943. result.push(nV4);
  60944. result.push(nV3.clone());
  60945. result.push(nV2.clone());
  60946. }
  60947. break;
  60948. case 2:
  60949. if (!v1Out) {
  60950. nV1 = vertices[index].clone();
  60951. nV2 = clipVertices(nV1, vertices[index + 1]);
  60952. nV3 = clipVertices(nV1, vertices[index + 2]);
  60953. result.push(nV1);
  60954. result.push(nV2);
  60955. result.push(nV3);
  60956. }
  60957. if (!v2Out) {
  60958. nV1 = vertices[index + 1].clone();
  60959. nV2 = clipVertices(nV1, vertices[index + 2]);
  60960. nV3 = clipVertices(nV1, vertices[index]);
  60961. result.push(nV1);
  60962. result.push(nV2);
  60963. result.push(nV3);
  60964. }
  60965. if (!v3Out) {
  60966. nV1 = vertices[index + 2].clone();
  60967. nV2 = clipVertices(nV1, vertices[index]);
  60968. nV3 = clipVertices(nV1, vertices[index + 1]);
  60969. result.push(nV1);
  60970. result.push(nV2);
  60971. result.push(nV3);
  60972. }
  60973. break;
  60974. case 3:
  60975. break;
  60976. }
  60977. }
  60978. return result;
  60979. };
  60980. for (var index = 0; index < indices.length; index += 3) {
  60981. var faceVertices = new Array();
  60982. faceVertices.push(extractDecalVector3(index));
  60983. faceVertices.push(extractDecalVector3(index + 1));
  60984. faceVertices.push(extractDecalVector3(index + 2));
  60985. // Clip
  60986. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60987. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60988. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60989. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60990. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60991. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60992. if (faceVertices.length === 0) {
  60993. continue;
  60994. }
  60995. // Add UVs and get back to world
  60996. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60997. var vertex = faceVertices[vIndex];
  60998. //TODO check for Int32Array | Uint32Array | Uint16Array
  60999. vertexData.indices.push(currentVertexDataIndex);
  61000. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61001. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61002. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61003. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61004. currentVertexDataIndex++;
  61005. }
  61006. }
  61007. // Return mesh
  61008. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61009. vertexData.applyToMesh(decal);
  61010. decal.position = position.clone();
  61011. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61012. return decal;
  61013. };
  61014. // Privates
  61015. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61016. // extrusion geometry
  61017. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61018. var tangents = path3D.getTangents();
  61019. var normals = path3D.getNormals();
  61020. var binormals = path3D.getBinormals();
  61021. var distances = path3D.getDistances();
  61022. var angle = 0;
  61023. var returnScale = function () { return scale !== null ? scale : 1; };
  61024. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61025. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61026. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61027. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61028. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61029. for (var i = 0; i < curve.length; i++) {
  61030. var shapePath = new Array();
  61031. var angleStep = rotate(i, distances[i]);
  61032. var scaleRatio = scl(i, distances[i]);
  61033. for (var p = 0; p < shape.length; p++) {
  61034. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61035. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61036. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61037. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61038. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61039. shapePath[p] = rotated;
  61040. }
  61041. shapePaths[index] = shapePath;
  61042. angle += angleStep;
  61043. index++;
  61044. }
  61045. // cap
  61046. var capPath = function (shapePath) {
  61047. var pointCap = Array();
  61048. var barycenter = BABYLON.Vector3.Zero();
  61049. var i;
  61050. for (i = 0; i < shapePath.length; i++) {
  61051. barycenter.addInPlace(shapePath[i]);
  61052. }
  61053. barycenter.scaleInPlace(1.0 / shapePath.length);
  61054. for (i = 0; i < shapePath.length; i++) {
  61055. pointCap.push(barycenter);
  61056. }
  61057. return pointCap;
  61058. };
  61059. switch (cap) {
  61060. case BABYLON.Mesh.NO_CAP:
  61061. break;
  61062. case BABYLON.Mesh.CAP_START:
  61063. shapePaths[0] = capPath(shapePaths[2]);
  61064. shapePaths[1] = shapePaths[2];
  61065. break;
  61066. case BABYLON.Mesh.CAP_END:
  61067. shapePaths[index] = shapePaths[index - 1];
  61068. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61069. break;
  61070. case BABYLON.Mesh.CAP_ALL:
  61071. shapePaths[0] = capPath(shapePaths[2]);
  61072. shapePaths[1] = shapePaths[2];
  61073. shapePaths[index] = shapePaths[index - 1];
  61074. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61075. break;
  61076. default:
  61077. break;
  61078. }
  61079. return shapePaths;
  61080. };
  61081. var path3D;
  61082. var pathArray;
  61083. if (instance) { // instance update
  61084. path3D = (instance.path3D).update(curve);
  61085. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61086. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61087. return instance;
  61088. }
  61089. // extruded shape creation
  61090. path3D = new BABYLON.Path3D(curve);
  61091. var newShapePaths = new Array();
  61092. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61093. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61094. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61095. extrudedGeneric.pathArray = pathArray;
  61096. extrudedGeneric.path3D = path3D;
  61097. extrudedGeneric.cap = cap;
  61098. return extrudedGeneric;
  61099. };
  61100. return MeshBuilder;
  61101. }());
  61102. BABYLON.MeshBuilder = MeshBuilder;
  61103. })(BABYLON || (BABYLON = {}));
  61104. //# sourceMappingURL=babylon.meshBuilder.js.map
  61105. var BABYLON;
  61106. (function (BABYLON) {
  61107. /**
  61108. * Draco compression (https://google.github.io/draco/)
  61109. */
  61110. var DracoCompression = /** @class */ (function () {
  61111. /**
  61112. * Constructor
  61113. */
  61114. function DracoCompression() {
  61115. }
  61116. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61117. /**
  61118. * Returns true if the decoder is available.
  61119. */
  61120. get: function () {
  61121. if (typeof DracoDecoderModule !== "undefined") {
  61122. return true;
  61123. }
  61124. var decoder = DracoCompression.Configuration.decoder;
  61125. if (decoder) {
  61126. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61127. return true;
  61128. }
  61129. if (decoder.fallbackUrl) {
  61130. return true;
  61131. }
  61132. }
  61133. return false;
  61134. },
  61135. enumerable: true,
  61136. configurable: true
  61137. });
  61138. /**
  61139. * Stop all async operations and release resources.
  61140. */
  61141. DracoCompression.prototype.dispose = function () {
  61142. };
  61143. /**
  61144. * Decode Draco compressed mesh data to vertex data.
  61145. * @param data The array buffer view for the Draco compression data
  61146. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61147. * @returns A promise that resolves with the decoded vertex data
  61148. */
  61149. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61150. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61151. var module = wrappedModule.module;
  61152. var vertexData = new BABYLON.VertexData();
  61153. var buffer = new module.DecoderBuffer();
  61154. buffer.Init(data, data.byteLength);
  61155. var decoder = new module.Decoder();
  61156. var geometry;
  61157. var status;
  61158. try {
  61159. var type = decoder.GetEncodedGeometryType(buffer);
  61160. switch (type) {
  61161. case module.TRIANGULAR_MESH:
  61162. geometry = new module.Mesh();
  61163. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61164. break;
  61165. case module.POINT_CLOUD:
  61166. geometry = new module.PointCloud();
  61167. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61168. break;
  61169. default:
  61170. throw new Error("Invalid geometry type " + type);
  61171. }
  61172. if (!status.ok() || !geometry.ptr) {
  61173. throw new Error(status.error_msg());
  61174. }
  61175. var numPoints = geometry.num_points();
  61176. if (type === module.TRIANGULAR_MESH) {
  61177. var numFaces = geometry.num_faces();
  61178. var faceIndices = new module.DracoInt32Array();
  61179. try {
  61180. var indices = new Uint32Array(numFaces * 3);
  61181. for (var i = 0; i < numFaces; i++) {
  61182. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61183. var offset = i * 3;
  61184. indices[offset + 0] = faceIndices.GetValue(0);
  61185. indices[offset + 1] = faceIndices.GetValue(1);
  61186. indices[offset + 2] = faceIndices.GetValue(2);
  61187. }
  61188. vertexData.indices = indices;
  61189. }
  61190. finally {
  61191. module.destroy(faceIndices);
  61192. }
  61193. }
  61194. for (var kind in attributes) {
  61195. var uniqueId = attributes[kind];
  61196. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61197. var dracoData = new module.DracoFloat32Array();
  61198. try {
  61199. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61200. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61201. for (var i = 0; i < babylonData.length; i++) {
  61202. babylonData[i] = dracoData.GetValue(i);
  61203. }
  61204. vertexData.set(babylonData, kind);
  61205. }
  61206. finally {
  61207. module.destroy(dracoData);
  61208. }
  61209. }
  61210. }
  61211. finally {
  61212. if (geometry) {
  61213. module.destroy(geometry);
  61214. }
  61215. module.destroy(decoder);
  61216. module.destroy(buffer);
  61217. }
  61218. return vertexData;
  61219. });
  61220. };
  61221. DracoCompression._GetDecoderModule = function () {
  61222. if (!DracoCompression._DecoderModulePromise) {
  61223. var promise = null;
  61224. var config_1 = {};
  61225. if (typeof DracoDecoderModule !== "undefined") {
  61226. promise = Promise.resolve();
  61227. }
  61228. else {
  61229. var decoder = DracoCompression.Configuration.decoder;
  61230. if (decoder) {
  61231. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61232. promise = Promise.all([
  61233. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61234. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61235. config_1.wasmBinary = data;
  61236. })
  61237. ]);
  61238. }
  61239. else if (decoder.fallbackUrl) {
  61240. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61241. }
  61242. }
  61243. }
  61244. if (!promise) {
  61245. throw new Error("Draco decoder module is not available");
  61246. }
  61247. DracoCompression._DecoderModulePromise = promise.then(function () {
  61248. return new Promise(function (resolve) {
  61249. config_1.onModuleLoaded = function (decoderModule) {
  61250. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61251. resolve({ module: decoderModule });
  61252. };
  61253. DracoDecoderModule(config_1);
  61254. });
  61255. });
  61256. }
  61257. return DracoCompression._DecoderModulePromise;
  61258. };
  61259. DracoCompression._LoadScriptAsync = function (url) {
  61260. return new Promise(function (resolve, reject) {
  61261. BABYLON.Tools.LoadScript(url, function () {
  61262. resolve();
  61263. }, function (message) {
  61264. reject(new Error(message));
  61265. });
  61266. });
  61267. };
  61268. DracoCompression._LoadFileAsync = function (url) {
  61269. return new Promise(function (resolve, reject) {
  61270. BABYLON.Tools.LoadFile(url, function (data) {
  61271. resolve(data);
  61272. }, undefined, undefined, true, function (request, exception) {
  61273. reject(exception);
  61274. });
  61275. });
  61276. };
  61277. /**
  61278. * The configuration.
  61279. */
  61280. DracoCompression.Configuration = {
  61281. decoder: {
  61282. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61283. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61284. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61285. }
  61286. };
  61287. return DracoCompression;
  61288. }());
  61289. BABYLON.DracoCompression = DracoCompression;
  61290. })(BABYLON || (BABYLON = {}));
  61291. //# sourceMappingURL=babylon.dracoCompression.js.map
  61292. var BABYLON;
  61293. (function (BABYLON) {
  61294. var AudioEngine = /** @class */ (function () {
  61295. function AudioEngine() {
  61296. this._audioContext = null;
  61297. this._audioContextInitialized = false;
  61298. this.canUseWebAudio = false;
  61299. this.WarnedWebAudioUnsupported = false;
  61300. this.unlocked = false;
  61301. this.isMP3supported = false;
  61302. this.isOGGsupported = false;
  61303. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61304. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61305. this.canUseWebAudio = true;
  61306. }
  61307. var audioElem = document.createElement('audio');
  61308. try {
  61309. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61310. this.isMP3supported = true;
  61311. }
  61312. }
  61313. catch (e) {
  61314. // protect error during capability check.
  61315. }
  61316. try {
  61317. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61318. this.isOGGsupported = true;
  61319. }
  61320. }
  61321. catch (e) {
  61322. // protect error during capability check.
  61323. }
  61324. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61325. this._unlockiOSaudio();
  61326. }
  61327. else {
  61328. this.unlocked = true;
  61329. }
  61330. }
  61331. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61332. get: function () {
  61333. if (!this._audioContextInitialized) {
  61334. this._initializeAudioContext();
  61335. }
  61336. return this._audioContext;
  61337. },
  61338. enumerable: true,
  61339. configurable: true
  61340. });
  61341. AudioEngine.prototype._unlockiOSaudio = function () {
  61342. var _this = this;
  61343. var unlockaudio = function () {
  61344. if (!_this.audioContext) {
  61345. return;
  61346. }
  61347. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61348. var source = _this.audioContext.createBufferSource();
  61349. source.buffer = buffer;
  61350. source.connect(_this.audioContext.destination);
  61351. source.start(0);
  61352. setTimeout(function () {
  61353. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61354. _this.unlocked = true;
  61355. window.removeEventListener('touchend', unlockaudio, false);
  61356. if (_this.onAudioUnlocked) {
  61357. _this.onAudioUnlocked();
  61358. }
  61359. }
  61360. }, 0);
  61361. };
  61362. window.addEventListener('touchend', unlockaudio, false);
  61363. };
  61364. AudioEngine.prototype._initializeAudioContext = function () {
  61365. try {
  61366. if (this.canUseWebAudio) {
  61367. this._audioContext = new AudioContext();
  61368. // create a global volume gain node
  61369. this.masterGain = this._audioContext.createGain();
  61370. this.masterGain.gain.value = 1;
  61371. this.masterGain.connect(this._audioContext.destination);
  61372. this._audioContextInitialized = true;
  61373. }
  61374. }
  61375. catch (e) {
  61376. this.canUseWebAudio = false;
  61377. BABYLON.Tools.Error("Web Audio: " + e.message);
  61378. }
  61379. };
  61380. AudioEngine.prototype.dispose = function () {
  61381. if (this.canUseWebAudio && this._audioContextInitialized) {
  61382. if (this._connectedAnalyser && this._audioContext) {
  61383. this._connectedAnalyser.stopDebugCanvas();
  61384. this._connectedAnalyser.dispose();
  61385. this.masterGain.disconnect();
  61386. this.masterGain.connect(this._audioContext.destination);
  61387. this._connectedAnalyser = null;
  61388. }
  61389. this.masterGain.gain.value = 1;
  61390. }
  61391. this.WarnedWebAudioUnsupported = false;
  61392. };
  61393. AudioEngine.prototype.getGlobalVolume = function () {
  61394. if (this.canUseWebAudio && this._audioContextInitialized) {
  61395. return this.masterGain.gain.value;
  61396. }
  61397. else {
  61398. return -1;
  61399. }
  61400. };
  61401. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61402. if (this.canUseWebAudio && this._audioContextInitialized) {
  61403. this.masterGain.gain.value = newVolume;
  61404. }
  61405. };
  61406. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61407. if (this._connectedAnalyser) {
  61408. this._connectedAnalyser.stopDebugCanvas();
  61409. }
  61410. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61411. this._connectedAnalyser = analyser;
  61412. this.masterGain.disconnect();
  61413. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61414. }
  61415. };
  61416. return AudioEngine;
  61417. }());
  61418. BABYLON.AudioEngine = AudioEngine;
  61419. })(BABYLON || (BABYLON = {}));
  61420. //# sourceMappingURL=babylon.audioEngine.js.map
  61421. var BABYLON;
  61422. (function (BABYLON) {
  61423. var Sound = /** @class */ (function () {
  61424. /**
  61425. * Create a sound and attach it to a scene
  61426. * @param name Name of your sound
  61427. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61428. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61429. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61430. */
  61431. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61432. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61433. var _this = this;
  61434. this.autoplay = false;
  61435. this.loop = false;
  61436. this.useCustomAttenuation = false;
  61437. this.spatialSound = false;
  61438. this.refDistance = 1;
  61439. this.rolloffFactor = 1;
  61440. this.maxDistance = 100;
  61441. this.distanceModel = "linear";
  61442. this._panningModel = "equalpower";
  61443. this._playbackRate = 1;
  61444. this._streaming = false;
  61445. this._startTime = 0;
  61446. this._startOffset = 0;
  61447. this._position = BABYLON.Vector3.Zero();
  61448. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61449. this._volume = 1;
  61450. this._isReadyToPlay = false;
  61451. this.isPlaying = false;
  61452. this.isPaused = false;
  61453. this._isDirectional = false;
  61454. // Used if you'd like to create a directional sound.
  61455. // If not set, the sound will be omnidirectional
  61456. this._coneInnerAngle = 360;
  61457. this._coneOuterAngle = 360;
  61458. this._coneOuterGain = 0;
  61459. this._isOutputConnected = false;
  61460. this._urlType = "Unknown";
  61461. this.name = name;
  61462. this._scene = scene;
  61463. this._readyToPlayCallback = readyToPlayCallback;
  61464. // Default custom attenuation function is a linear attenuation
  61465. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61466. if (currentDistance < maxDistance) {
  61467. return currentVolume * (1 - currentDistance / maxDistance);
  61468. }
  61469. else {
  61470. return 0;
  61471. }
  61472. };
  61473. if (options) {
  61474. this.autoplay = options.autoplay || false;
  61475. this.loop = options.loop || false;
  61476. // if volume === 0, we need another way to check this option
  61477. if (options.volume !== undefined) {
  61478. this._volume = options.volume;
  61479. }
  61480. this.spatialSound = options.spatialSound || false;
  61481. this.maxDistance = options.maxDistance || 100;
  61482. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61483. this.rolloffFactor = options.rolloffFactor || 1;
  61484. this.refDistance = options.refDistance || 1;
  61485. this.distanceModel = options.distanceModel || "linear";
  61486. this._playbackRate = options.playbackRate || 1;
  61487. this._streaming = options.streaming || false;
  61488. }
  61489. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61490. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61491. this._soundGain.gain.value = this._volume;
  61492. this._inputAudioNode = this._soundGain;
  61493. this._ouputAudioNode = this._soundGain;
  61494. if (this.spatialSound) {
  61495. this._createSpatialParameters();
  61496. }
  61497. this._scene.mainSoundTrack.AddSound(this);
  61498. var validParameter = true;
  61499. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61500. if (urlOrArrayBuffer) {
  61501. try {
  61502. if (typeof (urlOrArrayBuffer) === "string")
  61503. this._urlType = "String";
  61504. if (Array.isArray(urlOrArrayBuffer))
  61505. this._urlType = "Array";
  61506. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61507. this._urlType = "ArrayBuffer";
  61508. var urls = [];
  61509. var codecSupportedFound = false;
  61510. switch (this._urlType) {
  61511. case "ArrayBuffer":
  61512. if (urlOrArrayBuffer.byteLength > 0) {
  61513. codecSupportedFound = true;
  61514. this._soundLoaded(urlOrArrayBuffer);
  61515. }
  61516. break;
  61517. case "String":
  61518. urls.push(urlOrArrayBuffer);
  61519. case "Array":
  61520. if (urls.length === 0)
  61521. urls = urlOrArrayBuffer;
  61522. // If we found a supported format, we load it immediately and stop the loop
  61523. for (var i = 0; i < urls.length; i++) {
  61524. var url = urls[i];
  61525. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61526. codecSupportedFound = true;
  61527. }
  61528. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61529. codecSupportedFound = true;
  61530. }
  61531. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61532. codecSupportedFound = true;
  61533. }
  61534. if (url.indexOf("blob:") !== -1) {
  61535. codecSupportedFound = true;
  61536. }
  61537. if (codecSupportedFound) {
  61538. // Loading sound using XHR2
  61539. if (!this._streaming) {
  61540. this._scene._loadFile(url, function (data) {
  61541. _this._soundLoaded(data);
  61542. }, undefined, true, true, function (exception) {
  61543. if (exception) {
  61544. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61545. }
  61546. BABYLON.Tools.Error("Sound creation aborted.");
  61547. _this._scene.mainSoundTrack.RemoveSound(_this);
  61548. });
  61549. }
  61550. // Streaming sound using HTML5 Audio tag
  61551. else {
  61552. this._htmlAudioElement = new Audio(url);
  61553. this._htmlAudioElement.controls = false;
  61554. this._htmlAudioElement.loop = this.loop;
  61555. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61556. this._htmlAudioElement.preload = "auto";
  61557. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61558. _this._isReadyToPlay = true;
  61559. if (_this.autoplay) {
  61560. _this.play();
  61561. }
  61562. if (_this._readyToPlayCallback) {
  61563. _this._readyToPlayCallback();
  61564. }
  61565. });
  61566. document.body.appendChild(this._htmlAudioElement);
  61567. }
  61568. break;
  61569. }
  61570. }
  61571. break;
  61572. default:
  61573. validParameter = false;
  61574. break;
  61575. }
  61576. if (!validParameter) {
  61577. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61578. }
  61579. else {
  61580. if (!codecSupportedFound) {
  61581. this._isReadyToPlay = true;
  61582. // Simulating a ready to play event to avoid breaking code path
  61583. if (this._readyToPlayCallback) {
  61584. window.setTimeout(function () {
  61585. if (_this._readyToPlayCallback) {
  61586. _this._readyToPlayCallback();
  61587. }
  61588. }, 1000);
  61589. }
  61590. }
  61591. }
  61592. }
  61593. catch (ex) {
  61594. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61595. this._scene.mainSoundTrack.RemoveSound(this);
  61596. }
  61597. }
  61598. }
  61599. else {
  61600. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61601. this._scene.mainSoundTrack.AddSound(this);
  61602. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61603. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61604. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61605. }
  61606. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61607. if (this._readyToPlayCallback) {
  61608. window.setTimeout(function () {
  61609. if (_this._readyToPlayCallback) {
  61610. _this._readyToPlayCallback();
  61611. }
  61612. }, 1000);
  61613. }
  61614. }
  61615. }
  61616. Sound.prototype.dispose = function () {
  61617. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61618. if (this.isPlaying) {
  61619. this.stop();
  61620. }
  61621. this._isReadyToPlay = false;
  61622. if (this.soundTrackId === -1) {
  61623. this._scene.mainSoundTrack.RemoveSound(this);
  61624. }
  61625. else {
  61626. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61627. }
  61628. if (this._soundGain) {
  61629. this._soundGain.disconnect();
  61630. this._soundGain = null;
  61631. }
  61632. if (this._soundPanner) {
  61633. this._soundPanner.disconnect();
  61634. this._soundPanner = null;
  61635. }
  61636. if (this._soundSource) {
  61637. this._soundSource.disconnect();
  61638. this._soundSource = null;
  61639. }
  61640. this._audioBuffer = null;
  61641. if (this._htmlAudioElement) {
  61642. this._htmlAudioElement.pause();
  61643. this._htmlAudioElement.src = "";
  61644. document.body.removeChild(this._htmlAudioElement);
  61645. }
  61646. if (this._connectedMesh && this._registerFunc) {
  61647. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61648. this._connectedMesh = null;
  61649. }
  61650. }
  61651. };
  61652. Sound.prototype.isReady = function () {
  61653. return this._isReadyToPlay;
  61654. };
  61655. Sound.prototype._soundLoaded = function (audioData) {
  61656. var _this = this;
  61657. if (!BABYLON.Engine.audioEngine.audioContext) {
  61658. return;
  61659. }
  61660. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61661. _this._audioBuffer = buffer;
  61662. _this._isReadyToPlay = true;
  61663. if (_this.autoplay) {
  61664. _this.play();
  61665. }
  61666. if (_this._readyToPlayCallback) {
  61667. _this._readyToPlayCallback();
  61668. }
  61669. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61670. };
  61671. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61673. this._audioBuffer = audioBuffer;
  61674. this._isReadyToPlay = true;
  61675. }
  61676. };
  61677. Sound.prototype.updateOptions = function (options) {
  61678. if (options) {
  61679. this.loop = options.loop || this.loop;
  61680. this.maxDistance = options.maxDistance || this.maxDistance;
  61681. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61682. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61683. this.refDistance = options.refDistance || this.refDistance;
  61684. this.distanceModel = options.distanceModel || this.distanceModel;
  61685. this._playbackRate = options.playbackRate || this._playbackRate;
  61686. this._updateSpatialParameters();
  61687. if (this.isPlaying) {
  61688. if (this._streaming) {
  61689. this._htmlAudioElement.playbackRate = this._playbackRate;
  61690. }
  61691. else {
  61692. if (this._soundSource) {
  61693. this._soundSource.playbackRate.value = this._playbackRate;
  61694. }
  61695. }
  61696. }
  61697. }
  61698. };
  61699. Sound.prototype._createSpatialParameters = function () {
  61700. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61701. if (this._scene.headphone) {
  61702. this._panningModel = "HRTF";
  61703. }
  61704. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61705. this._updateSpatialParameters();
  61706. this._soundPanner.connect(this._ouputAudioNode);
  61707. this._inputAudioNode = this._soundPanner;
  61708. }
  61709. };
  61710. Sound.prototype._updateSpatialParameters = function () {
  61711. if (this.spatialSound && this._soundPanner) {
  61712. if (this.useCustomAttenuation) {
  61713. // Tricks to disable in a way embedded Web Audio attenuation
  61714. this._soundPanner.distanceModel = "linear";
  61715. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61716. this._soundPanner.refDistance = 1;
  61717. this._soundPanner.rolloffFactor = 1;
  61718. this._soundPanner.panningModel = this._panningModel;
  61719. }
  61720. else {
  61721. this._soundPanner.distanceModel = this.distanceModel;
  61722. this._soundPanner.maxDistance = this.maxDistance;
  61723. this._soundPanner.refDistance = this.refDistance;
  61724. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61725. this._soundPanner.panningModel = this._panningModel;
  61726. }
  61727. }
  61728. };
  61729. Sound.prototype.switchPanningModelToHRTF = function () {
  61730. this._panningModel = "HRTF";
  61731. this._switchPanningModel();
  61732. };
  61733. Sound.prototype.switchPanningModelToEqualPower = function () {
  61734. this._panningModel = "equalpower";
  61735. this._switchPanningModel();
  61736. };
  61737. Sound.prototype._switchPanningModel = function () {
  61738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61739. this._soundPanner.panningModel = this._panningModel;
  61740. }
  61741. };
  61742. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61743. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61744. if (this._isOutputConnected) {
  61745. this._ouputAudioNode.disconnect();
  61746. }
  61747. this._ouputAudioNode.connect(soundTrackAudioNode);
  61748. this._isOutputConnected = true;
  61749. }
  61750. };
  61751. /**
  61752. * Transform this sound into a directional source
  61753. * @param coneInnerAngle Size of the inner cone in degree
  61754. * @param coneOuterAngle Size of the outer cone in degree
  61755. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61756. */
  61757. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61758. if (coneOuterAngle < coneInnerAngle) {
  61759. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61760. return;
  61761. }
  61762. this._coneInnerAngle = coneInnerAngle;
  61763. this._coneOuterAngle = coneOuterAngle;
  61764. this._coneOuterGain = coneOuterGain;
  61765. this._isDirectional = true;
  61766. if (this.isPlaying && this.loop) {
  61767. this.stop();
  61768. this.play();
  61769. }
  61770. };
  61771. Sound.prototype.setPosition = function (newPosition) {
  61772. this._position = newPosition;
  61773. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61774. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61775. }
  61776. };
  61777. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61778. this._localDirection = newLocalDirection;
  61779. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61780. this._updateDirection();
  61781. }
  61782. };
  61783. Sound.prototype._updateDirection = function () {
  61784. if (!this._connectedMesh || !this._soundPanner) {
  61785. return;
  61786. }
  61787. var mat = this._connectedMesh.getWorldMatrix();
  61788. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61789. direction.normalize();
  61790. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61791. };
  61792. Sound.prototype.updateDistanceFromListener = function () {
  61793. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61794. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61795. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61796. }
  61797. };
  61798. Sound.prototype.setAttenuationFunction = function (callback) {
  61799. this._customAttenuationFunction = callback;
  61800. };
  61801. /**
  61802. * Play the sound
  61803. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61804. * @param offset (optional) Start the sound setting it at a specific time
  61805. */
  61806. Sound.prototype.play = function (time, offset) {
  61807. var _this = this;
  61808. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61809. try {
  61810. if (this._startOffset < 0) {
  61811. time = -this._startOffset;
  61812. this._startOffset = 0;
  61813. }
  61814. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61815. if (!this._soundSource || !this._streamingSource) {
  61816. if (this.spatialSound && this._soundPanner) {
  61817. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61818. if (this._isDirectional) {
  61819. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61820. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61821. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61822. if (this._connectedMesh) {
  61823. this._updateDirection();
  61824. }
  61825. else {
  61826. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61827. }
  61828. }
  61829. }
  61830. }
  61831. if (this._streaming) {
  61832. if (!this._streamingSource) {
  61833. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61834. this._htmlAudioElement.onended = function () { _this._onended(); };
  61835. this._htmlAudioElement.playbackRate = this._playbackRate;
  61836. }
  61837. this._streamingSource.disconnect();
  61838. this._streamingSource.connect(this._inputAudioNode);
  61839. this._htmlAudioElement.play();
  61840. }
  61841. else {
  61842. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61843. this._soundSource.buffer = this._audioBuffer;
  61844. this._soundSource.connect(this._inputAudioNode);
  61845. this._soundSource.loop = this.loop;
  61846. this._soundSource.playbackRate.value = this._playbackRate;
  61847. this._soundSource.onended = function () { _this._onended(); };
  61848. if (this._soundSource.buffer) {
  61849. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61850. }
  61851. }
  61852. this._startTime = startTime;
  61853. this.isPlaying = true;
  61854. this.isPaused = false;
  61855. }
  61856. catch (ex) {
  61857. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61858. }
  61859. }
  61860. };
  61861. Sound.prototype._onended = function () {
  61862. this.isPlaying = false;
  61863. if (this.onended) {
  61864. this.onended();
  61865. }
  61866. };
  61867. /**
  61868. * Stop the sound
  61869. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61870. */
  61871. Sound.prototype.stop = function (time) {
  61872. if (this.isPlaying) {
  61873. if (this._streaming) {
  61874. this._htmlAudioElement.pause();
  61875. // Test needed for Firefox or it will generate an Invalid State Error
  61876. if (this._htmlAudioElement.currentTime > 0) {
  61877. this._htmlAudioElement.currentTime = 0;
  61878. }
  61879. }
  61880. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61881. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61882. this._soundSource.stop(stopTime);
  61883. this._soundSource.onended = function () { };
  61884. if (!this.isPaused) {
  61885. this._startOffset = 0;
  61886. }
  61887. }
  61888. this.isPlaying = false;
  61889. }
  61890. };
  61891. Sound.prototype.pause = function () {
  61892. if (this.isPlaying) {
  61893. this.isPaused = true;
  61894. if (this._streaming) {
  61895. this._htmlAudioElement.pause();
  61896. }
  61897. else if (BABYLON.Engine.audioEngine.audioContext) {
  61898. this.stop(0);
  61899. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61900. }
  61901. }
  61902. };
  61903. Sound.prototype.setVolume = function (newVolume, time) {
  61904. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61905. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61906. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61907. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61908. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61909. }
  61910. else {
  61911. this._soundGain.gain.value = newVolume;
  61912. }
  61913. }
  61914. this._volume = newVolume;
  61915. };
  61916. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61917. this._playbackRate = newPlaybackRate;
  61918. if (this.isPlaying) {
  61919. if (this._streaming) {
  61920. this._htmlAudioElement.playbackRate = this._playbackRate;
  61921. }
  61922. else if (this._soundSource) {
  61923. this._soundSource.playbackRate.value = this._playbackRate;
  61924. }
  61925. }
  61926. };
  61927. Sound.prototype.getVolume = function () {
  61928. return this._volume;
  61929. };
  61930. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61931. var _this = this;
  61932. if (this._connectedMesh && this._registerFunc) {
  61933. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61934. this._registerFunc = null;
  61935. }
  61936. this._connectedMesh = meshToConnectTo;
  61937. if (!this.spatialSound) {
  61938. this.spatialSound = true;
  61939. this._createSpatialParameters();
  61940. if (this.isPlaying && this.loop) {
  61941. this.stop();
  61942. this.play();
  61943. }
  61944. }
  61945. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61946. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61947. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61948. };
  61949. Sound.prototype.detachFromMesh = function () {
  61950. if (this._connectedMesh && this._registerFunc) {
  61951. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61952. this._registerFunc = null;
  61953. this._connectedMesh = null;
  61954. }
  61955. };
  61956. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61957. if (!node.getBoundingInfo) {
  61958. return;
  61959. }
  61960. var mesh = node;
  61961. var boundingInfo = mesh.getBoundingInfo();
  61962. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61963. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61964. this._updateDirection();
  61965. }
  61966. };
  61967. Sound.prototype.clone = function () {
  61968. var _this = this;
  61969. if (!this._streaming) {
  61970. var setBufferAndRun = function () {
  61971. if (_this._isReadyToPlay) {
  61972. clonedSound._audioBuffer = _this.getAudioBuffer();
  61973. clonedSound._isReadyToPlay = true;
  61974. if (clonedSound.autoplay) {
  61975. clonedSound.play();
  61976. }
  61977. }
  61978. else {
  61979. window.setTimeout(setBufferAndRun, 300);
  61980. }
  61981. };
  61982. var currentOptions = {
  61983. autoplay: this.autoplay, loop: this.loop,
  61984. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61985. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61986. refDistance: this.refDistance, distanceModel: this.distanceModel
  61987. };
  61988. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61989. if (this.useCustomAttenuation) {
  61990. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61991. }
  61992. clonedSound.setPosition(this._position);
  61993. clonedSound.setPlaybackRate(this._playbackRate);
  61994. setBufferAndRun();
  61995. return clonedSound;
  61996. }
  61997. // Can't clone a streaming sound
  61998. else {
  61999. return null;
  62000. }
  62001. };
  62002. Sound.prototype.getAudioBuffer = function () {
  62003. return this._audioBuffer;
  62004. };
  62005. Sound.prototype.serialize = function () {
  62006. var serializationObject = {
  62007. name: this.name,
  62008. url: this.name,
  62009. autoplay: this.autoplay,
  62010. loop: this.loop,
  62011. volume: this._volume,
  62012. spatialSound: this.spatialSound,
  62013. maxDistance: this.maxDistance,
  62014. rolloffFactor: this.rolloffFactor,
  62015. refDistance: this.refDistance,
  62016. distanceModel: this.distanceModel,
  62017. playbackRate: this._playbackRate,
  62018. panningModel: this._panningModel,
  62019. soundTrackId: this.soundTrackId
  62020. };
  62021. if (this.spatialSound) {
  62022. if (this._connectedMesh)
  62023. serializationObject.connectedMeshId = this._connectedMesh.id;
  62024. serializationObject.position = this._position.asArray();
  62025. serializationObject.refDistance = this.refDistance;
  62026. serializationObject.distanceModel = this.distanceModel;
  62027. serializationObject.isDirectional = this._isDirectional;
  62028. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62029. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62030. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62031. serializationObject.coneOuterGain = this._coneOuterGain;
  62032. }
  62033. return serializationObject;
  62034. };
  62035. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62036. var soundName = parsedSound.name;
  62037. var soundUrl;
  62038. if (parsedSound.url) {
  62039. soundUrl = rootUrl + parsedSound.url;
  62040. }
  62041. else {
  62042. soundUrl = rootUrl + soundName;
  62043. }
  62044. var options = {
  62045. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62046. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62047. rolloffFactor: parsedSound.rolloffFactor,
  62048. refDistance: parsedSound.refDistance,
  62049. distanceModel: parsedSound.distanceModel,
  62050. playbackRate: parsedSound.playbackRate
  62051. };
  62052. var newSound;
  62053. if (!sourceSound) {
  62054. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62055. scene._addPendingData(newSound);
  62056. }
  62057. else {
  62058. var setBufferAndRun = function () {
  62059. if (sourceSound._isReadyToPlay) {
  62060. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62061. newSound._isReadyToPlay = true;
  62062. if (newSound.autoplay) {
  62063. newSound.play();
  62064. }
  62065. }
  62066. else {
  62067. window.setTimeout(setBufferAndRun, 300);
  62068. }
  62069. };
  62070. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62071. setBufferAndRun();
  62072. }
  62073. if (parsedSound.position) {
  62074. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62075. newSound.setPosition(soundPosition);
  62076. }
  62077. if (parsedSound.isDirectional) {
  62078. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62079. if (parsedSound.localDirectionToMesh) {
  62080. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62081. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62082. }
  62083. }
  62084. if (parsedSound.connectedMeshId) {
  62085. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62086. if (connectedMesh) {
  62087. newSound.attachToMesh(connectedMesh);
  62088. }
  62089. }
  62090. return newSound;
  62091. };
  62092. return Sound;
  62093. }());
  62094. BABYLON.Sound = Sound;
  62095. })(BABYLON || (BABYLON = {}));
  62096. //# sourceMappingURL=babylon.sound.js.map
  62097. var BABYLON;
  62098. (function (BABYLON) {
  62099. var SoundTrack = /** @class */ (function () {
  62100. function SoundTrack(scene, options) {
  62101. this.id = -1;
  62102. this._isMainTrack = false;
  62103. this._isInitialized = false;
  62104. this._scene = scene;
  62105. this.soundCollection = new Array();
  62106. this._options = options;
  62107. if (!this._isMainTrack) {
  62108. this._scene.soundTracks.push(this);
  62109. this.id = this._scene.soundTracks.length - 1;
  62110. }
  62111. }
  62112. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62113. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62114. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62115. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62116. if (this._options) {
  62117. if (this._options.volume) {
  62118. this._outputAudioNode.gain.value = this._options.volume;
  62119. }
  62120. if (this._options.mainTrack) {
  62121. this._isMainTrack = this._options.mainTrack;
  62122. }
  62123. }
  62124. this._isInitialized = true;
  62125. }
  62126. };
  62127. SoundTrack.prototype.dispose = function () {
  62128. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62129. if (this._connectedAnalyser) {
  62130. this._connectedAnalyser.stopDebugCanvas();
  62131. }
  62132. while (this.soundCollection.length) {
  62133. this.soundCollection[0].dispose();
  62134. }
  62135. if (this._outputAudioNode) {
  62136. this._outputAudioNode.disconnect();
  62137. }
  62138. this._outputAudioNode = null;
  62139. }
  62140. };
  62141. SoundTrack.prototype.AddSound = function (sound) {
  62142. if (!this._isInitialized) {
  62143. this._initializeSoundTrackAudioGraph();
  62144. }
  62145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62146. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62147. }
  62148. if (sound.soundTrackId) {
  62149. if (sound.soundTrackId === -1) {
  62150. this._scene.mainSoundTrack.RemoveSound(sound);
  62151. }
  62152. else {
  62153. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62154. }
  62155. }
  62156. this.soundCollection.push(sound);
  62157. sound.soundTrackId = this.id;
  62158. };
  62159. SoundTrack.prototype.RemoveSound = function (sound) {
  62160. var index = this.soundCollection.indexOf(sound);
  62161. if (index !== -1) {
  62162. this.soundCollection.splice(index, 1);
  62163. }
  62164. };
  62165. SoundTrack.prototype.setVolume = function (newVolume) {
  62166. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62167. this._outputAudioNode.gain.value = newVolume;
  62168. }
  62169. };
  62170. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62171. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62172. for (var i = 0; i < this.soundCollection.length; i++) {
  62173. this.soundCollection[i].switchPanningModelToHRTF();
  62174. }
  62175. }
  62176. };
  62177. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62178. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62179. for (var i = 0; i < this.soundCollection.length; i++) {
  62180. this.soundCollection[i].switchPanningModelToEqualPower();
  62181. }
  62182. }
  62183. };
  62184. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62185. if (this._connectedAnalyser) {
  62186. this._connectedAnalyser.stopDebugCanvas();
  62187. }
  62188. this._connectedAnalyser = analyser;
  62189. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62190. this._outputAudioNode.disconnect();
  62191. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62192. }
  62193. };
  62194. return SoundTrack;
  62195. }());
  62196. BABYLON.SoundTrack = SoundTrack;
  62197. })(BABYLON || (BABYLON = {}));
  62198. //# sourceMappingURL=babylon.soundtrack.js.map
  62199. var BABYLON;
  62200. (function (BABYLON) {
  62201. var Analyser = /** @class */ (function () {
  62202. function Analyser(scene) {
  62203. this.SMOOTHING = 0.75;
  62204. this.FFT_SIZE = 512;
  62205. this.BARGRAPHAMPLITUDE = 256;
  62206. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62207. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62208. this._scene = scene;
  62209. this._audioEngine = BABYLON.Engine.audioEngine;
  62210. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62211. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62212. this._webAudioAnalyser.minDecibels = -140;
  62213. this._webAudioAnalyser.maxDecibels = 0;
  62214. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62215. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62216. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62217. }
  62218. }
  62219. Analyser.prototype.getFrequencyBinCount = function () {
  62220. if (this._audioEngine.canUseWebAudio) {
  62221. return this._webAudioAnalyser.frequencyBinCount;
  62222. }
  62223. else {
  62224. return 0;
  62225. }
  62226. };
  62227. Analyser.prototype.getByteFrequencyData = function () {
  62228. if (this._audioEngine.canUseWebAudio) {
  62229. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62230. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62231. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62232. }
  62233. return this._byteFreqs;
  62234. };
  62235. Analyser.prototype.getByteTimeDomainData = function () {
  62236. if (this._audioEngine.canUseWebAudio) {
  62237. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62238. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62239. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62240. }
  62241. return this._byteTime;
  62242. };
  62243. Analyser.prototype.getFloatFrequencyData = function () {
  62244. if (this._audioEngine.canUseWebAudio) {
  62245. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62246. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62247. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62248. }
  62249. return this._floatFreqs;
  62250. };
  62251. Analyser.prototype.drawDebugCanvas = function () {
  62252. var _this = this;
  62253. if (this._audioEngine.canUseWebAudio) {
  62254. if (!this._debugCanvas) {
  62255. this._debugCanvas = document.createElement("canvas");
  62256. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62257. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62258. this._debugCanvas.style.position = "absolute";
  62259. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62260. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62261. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62262. document.body.appendChild(this._debugCanvas);
  62263. this._registerFunc = function () {
  62264. _this.drawDebugCanvas();
  62265. };
  62266. this._scene.registerBeforeRender(this._registerFunc);
  62267. }
  62268. if (this._registerFunc && this._debugCanvasContext) {
  62269. var workingArray = this.getByteFrequencyData();
  62270. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62271. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62272. // Draw the frequency domain chart.
  62273. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62274. var value = workingArray[i];
  62275. var percent = value / this.BARGRAPHAMPLITUDE;
  62276. var height = this.DEBUGCANVASSIZE.height * percent;
  62277. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62278. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62279. var hue = i / this.getFrequencyBinCount() * 360;
  62280. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62281. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62282. }
  62283. }
  62284. }
  62285. };
  62286. Analyser.prototype.stopDebugCanvas = function () {
  62287. if (this._debugCanvas) {
  62288. if (this._registerFunc) {
  62289. this._scene.unregisterBeforeRender(this._registerFunc);
  62290. this._registerFunc = null;
  62291. }
  62292. document.body.removeChild(this._debugCanvas);
  62293. this._debugCanvas = null;
  62294. this._debugCanvasContext = null;
  62295. }
  62296. };
  62297. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62298. if (this._audioEngine.canUseWebAudio) {
  62299. inputAudioNode.connect(this._webAudioAnalyser);
  62300. this._webAudioAnalyser.connect(outputAudioNode);
  62301. }
  62302. };
  62303. Analyser.prototype.dispose = function () {
  62304. if (this._audioEngine.canUseWebAudio) {
  62305. this._webAudioAnalyser.disconnect();
  62306. }
  62307. };
  62308. return Analyser;
  62309. }());
  62310. BABYLON.Analyser = Analyser;
  62311. })(BABYLON || (BABYLON = {}));
  62312. //# sourceMappingURL=babylon.analyser.js.map
  62313. var BABYLON;
  62314. (function (BABYLON) {
  62315. var CubeTexture = /** @class */ (function (_super) {
  62316. __extends(CubeTexture, _super);
  62317. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62318. if (extensions === void 0) { extensions = null; }
  62319. if (noMipmap === void 0) { noMipmap = false; }
  62320. if (files === void 0) { files = null; }
  62321. if (onLoad === void 0) { onLoad = null; }
  62322. if (onError === void 0) { onError = null; }
  62323. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62324. if (prefiltered === void 0) { prefiltered = false; }
  62325. if (forcedExtension === void 0) { forcedExtension = null; }
  62326. var _this = _super.call(this, scene) || this;
  62327. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62328. /**
  62329. * Gets or sets the center of the bounding box associated with the cube texture
  62330. * It must define where the camera used to render the texture was set
  62331. */
  62332. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62333. _this._rotationY = 0;
  62334. _this.name = rootUrl;
  62335. _this.url = rootUrl;
  62336. _this._noMipmap = noMipmap;
  62337. _this.hasAlpha = false;
  62338. _this._format = format;
  62339. _this._prefiltered = prefiltered;
  62340. _this.isCube = true;
  62341. _this._textureMatrix = BABYLON.Matrix.Identity();
  62342. if (prefiltered) {
  62343. _this.gammaSpace = false;
  62344. }
  62345. if (!rootUrl && !files) {
  62346. return _this;
  62347. }
  62348. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62349. var lastDot = rootUrl.lastIndexOf(".");
  62350. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62351. var isDDS = (extension === ".dds");
  62352. if (!files) {
  62353. if (!isDDS && !extensions) {
  62354. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62355. }
  62356. files = [];
  62357. if (extensions) {
  62358. for (var index = 0; index < extensions.length; index++) {
  62359. files.push(rootUrl + extensions[index]);
  62360. }
  62361. }
  62362. }
  62363. _this._files = files;
  62364. if (!_this._texture) {
  62365. if (!scene.useDelayedTextureLoading) {
  62366. if (prefiltered) {
  62367. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62368. }
  62369. else {
  62370. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62371. }
  62372. }
  62373. else {
  62374. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62375. }
  62376. }
  62377. else if (onLoad) {
  62378. if (_this._texture.isReady) {
  62379. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62380. }
  62381. else {
  62382. _this._texture.onLoadedObservable.add(onLoad);
  62383. }
  62384. }
  62385. return _this;
  62386. }
  62387. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62388. get: function () {
  62389. return this._boundingBoxSize;
  62390. },
  62391. /**
  62392. * Gets or sets the size of the bounding box associated with the cube texture
  62393. * When defined, the cubemap will switch to local mode
  62394. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62395. * @example https://www.babylonjs-playground.com/#RNASML
  62396. */
  62397. set: function (value) {
  62398. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62399. return;
  62400. }
  62401. this._boundingBoxSize = value;
  62402. var scene = this.getScene();
  62403. if (scene) {
  62404. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62405. }
  62406. },
  62407. enumerable: true,
  62408. configurable: true
  62409. });
  62410. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62411. /**
  62412. * Gets texture matrix rotation angle around Y axis radians.
  62413. */
  62414. get: function () {
  62415. return this._rotationY;
  62416. },
  62417. /**
  62418. * Sets texture matrix rotation angle around Y axis in radians.
  62419. */
  62420. set: function (value) {
  62421. this._rotationY = value;
  62422. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62423. },
  62424. enumerable: true,
  62425. configurable: true
  62426. });
  62427. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62428. var rootUrlKey = "";
  62429. files.forEach(function (url) { return rootUrlKey += url; });
  62430. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62431. };
  62432. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62433. if (forcedExtension === void 0) { forcedExtension = null; }
  62434. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62435. };
  62436. // Methods
  62437. CubeTexture.prototype.delayLoad = function () {
  62438. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62439. return;
  62440. }
  62441. var scene = this.getScene();
  62442. if (!scene) {
  62443. return;
  62444. }
  62445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62446. this._texture = this._getFromCache(this.url, this._noMipmap);
  62447. if (!this._texture) {
  62448. if (this._prefiltered) {
  62449. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62450. }
  62451. else {
  62452. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62453. }
  62454. }
  62455. };
  62456. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62457. return this._textureMatrix;
  62458. };
  62459. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62460. this._textureMatrix = value;
  62461. };
  62462. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62463. var texture = BABYLON.SerializationHelper.Parse(function () {
  62464. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62465. }, parsedTexture, scene);
  62466. // Local Cubemaps
  62467. if (parsedTexture.boundingBoxPosition) {
  62468. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62469. }
  62470. if (parsedTexture.boundingBoxSize) {
  62471. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62472. }
  62473. // Animations
  62474. if (parsedTexture.animations) {
  62475. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62476. var parsedAnimation = parsedTexture.animations[animationIndex];
  62477. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62478. }
  62479. }
  62480. return texture;
  62481. };
  62482. CubeTexture.prototype.clone = function () {
  62483. var _this = this;
  62484. return BABYLON.SerializationHelper.Clone(function () {
  62485. var scene = _this.getScene();
  62486. if (!scene) {
  62487. return _this;
  62488. }
  62489. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62490. }, this);
  62491. };
  62492. __decorate([
  62493. BABYLON.serialize("rotationY")
  62494. ], CubeTexture.prototype, "_rotationY", void 0);
  62495. return CubeTexture;
  62496. }(BABYLON.BaseTexture));
  62497. BABYLON.CubeTexture = CubeTexture;
  62498. })(BABYLON || (BABYLON = {}));
  62499. //# sourceMappingURL=babylon.cubeTexture.js.map
  62500. var BABYLON;
  62501. (function (BABYLON) {
  62502. var RenderTargetTexture = /** @class */ (function (_super) {
  62503. __extends(RenderTargetTexture, _super);
  62504. /**
  62505. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62506. * or used a shadow, depth texture...
  62507. * @param name The friendly name of the texture
  62508. * @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)
  62509. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62510. * @param generateMipMaps True if mip maps need to be generated after render.
  62511. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62512. * @param type The type of the buffer in the RTT (int, half float, float...)
  62513. * @param isCube True if a cube texture needs to be created
  62514. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62515. * @param generateDepthBuffer True to generate a depth buffer
  62516. * @param generateStencilBuffer True to generate a stencil buffer
  62517. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62518. */
  62519. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62520. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62521. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62522. if (isCube === void 0) { isCube = false; }
  62523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62524. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62525. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62526. if (isMulti === void 0) { isMulti = false; }
  62527. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62528. _this.isCube = isCube;
  62529. /**
  62530. * Use this list to define the list of mesh you want to render.
  62531. */
  62532. _this.renderList = new Array();
  62533. _this.renderParticles = true;
  62534. _this.renderSprites = false;
  62535. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62536. _this.ignoreCameraViewport = false;
  62537. // Events
  62538. /**
  62539. * An event triggered when the texture is unbind.
  62540. */
  62541. _this.onBeforeBindObservable = new BABYLON.Observable();
  62542. /**
  62543. * An event triggered when the texture is unbind.
  62544. */
  62545. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62546. /**
  62547. * An event triggered before rendering the texture
  62548. */
  62549. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62550. /**
  62551. * An event triggered after rendering the texture
  62552. */
  62553. _this.onAfterRenderObservable = new BABYLON.Observable();
  62554. /**
  62555. * An event triggered after the texture clear
  62556. */
  62557. _this.onClearObservable = new BABYLON.Observable();
  62558. _this._currentRefreshId = -1;
  62559. _this._refreshRate = 1;
  62560. _this._samples = 1;
  62561. /**
  62562. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62563. * It must define where the camera used to render the texture is set
  62564. */
  62565. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62566. scene = _this.getScene();
  62567. if (!scene) {
  62568. return _this;
  62569. }
  62570. _this._engine = scene.getEngine();
  62571. _this.name = name;
  62572. _this.isRenderTarget = true;
  62573. _this._initialSizeParameter = size;
  62574. _this._processSizeParameter(size);
  62575. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62576. });
  62577. _this._generateMipMaps = generateMipMaps ? true : false;
  62578. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62579. // Rendering groups
  62580. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62581. if (isMulti) {
  62582. return _this;
  62583. }
  62584. _this._renderTargetOptions = {
  62585. generateMipMaps: generateMipMaps,
  62586. type: type,
  62587. samplingMode: samplingMode,
  62588. generateDepthBuffer: generateDepthBuffer,
  62589. generateStencilBuffer: generateStencilBuffer
  62590. };
  62591. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62592. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62593. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62594. }
  62595. if (isCube) {
  62596. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62597. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62598. _this._textureMatrix = BABYLON.Matrix.Identity();
  62599. }
  62600. else {
  62601. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62602. }
  62603. return _this;
  62604. }
  62605. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62606. get: function () {
  62607. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62613. get: function () {
  62614. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62615. },
  62616. enumerable: true,
  62617. configurable: true
  62618. });
  62619. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62620. get: function () {
  62621. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62622. },
  62623. enumerable: true,
  62624. configurable: true
  62625. });
  62626. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62627. set: function (callback) {
  62628. if (this._onAfterUnbindObserver) {
  62629. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62630. }
  62631. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62632. },
  62633. enumerable: true,
  62634. configurable: true
  62635. });
  62636. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62637. set: function (callback) {
  62638. if (this._onBeforeRenderObserver) {
  62639. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62640. }
  62641. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62642. },
  62643. enumerable: true,
  62644. configurable: true
  62645. });
  62646. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62647. set: function (callback) {
  62648. if (this._onAfterRenderObserver) {
  62649. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62650. }
  62651. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62652. },
  62653. enumerable: true,
  62654. configurable: true
  62655. });
  62656. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62657. set: function (callback) {
  62658. if (this._onClearObserver) {
  62659. this.onClearObservable.remove(this._onClearObserver);
  62660. }
  62661. this._onClearObserver = this.onClearObservable.add(callback);
  62662. },
  62663. enumerable: true,
  62664. configurable: true
  62665. });
  62666. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62667. get: function () {
  62668. return this._renderTargetOptions;
  62669. },
  62670. enumerable: true,
  62671. configurable: true
  62672. });
  62673. RenderTargetTexture.prototype._onRatioRescale = function () {
  62674. if (this._sizeRatio) {
  62675. this.resize(this._initialSizeParameter);
  62676. }
  62677. };
  62678. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62679. get: function () {
  62680. return this._boundingBoxSize;
  62681. },
  62682. /**
  62683. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62684. * When defined, the cubemap will switch to local mode
  62685. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62686. * @example https://www.babylonjs-playground.com/#RNASML
  62687. */
  62688. set: function (value) {
  62689. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62690. return;
  62691. }
  62692. this._boundingBoxSize = value;
  62693. var scene = this.getScene();
  62694. if (scene) {
  62695. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62696. }
  62697. },
  62698. enumerable: true,
  62699. configurable: true
  62700. });
  62701. /**
  62702. * Creates a depth stencil texture.
  62703. * This is only available in WebGL 2 or with the depth texture extension available.
  62704. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62705. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62706. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62707. */
  62708. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62709. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62710. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62711. if (generateStencil === void 0) { generateStencil = false; }
  62712. if (!this.getScene()) {
  62713. return;
  62714. }
  62715. var engine = this.getScene().getEngine();
  62716. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62717. bilinearFiltering: bilinearFiltering,
  62718. comparisonFunction: comparisonFunction,
  62719. generateStencil: generateStencil,
  62720. isCube: this.isCube
  62721. });
  62722. engine.setFrameBufferDepthStencilTexture(this);
  62723. };
  62724. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62725. if (size.ratio) {
  62726. this._sizeRatio = size.ratio;
  62727. this._size = {
  62728. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62729. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62730. };
  62731. }
  62732. else {
  62733. this._size = size;
  62734. }
  62735. };
  62736. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62737. get: function () {
  62738. return this._samples;
  62739. },
  62740. set: function (value) {
  62741. if (this._samples === value) {
  62742. return;
  62743. }
  62744. var scene = this.getScene();
  62745. if (!scene) {
  62746. return;
  62747. }
  62748. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62749. },
  62750. enumerable: true,
  62751. configurable: true
  62752. });
  62753. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62754. this._currentRefreshId = -1;
  62755. };
  62756. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62757. get: function () {
  62758. return this._refreshRate;
  62759. },
  62760. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62761. set: function (value) {
  62762. this._refreshRate = value;
  62763. this.resetRefreshCounter();
  62764. },
  62765. enumerable: true,
  62766. configurable: true
  62767. });
  62768. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62769. if (!this._postProcessManager) {
  62770. var scene = this.getScene();
  62771. if (!scene) {
  62772. return;
  62773. }
  62774. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62775. this._postProcesses = new Array();
  62776. }
  62777. this._postProcesses.push(postProcess);
  62778. this._postProcesses[0].autoClear = false;
  62779. };
  62780. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62781. if (!this._postProcesses) {
  62782. return;
  62783. }
  62784. if (dispose) {
  62785. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62786. var postProcess = _a[_i];
  62787. postProcess.dispose();
  62788. }
  62789. }
  62790. this._postProcesses = [];
  62791. };
  62792. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62793. if (!this._postProcesses) {
  62794. return;
  62795. }
  62796. var index = this._postProcesses.indexOf(postProcess);
  62797. if (index === -1) {
  62798. return;
  62799. }
  62800. this._postProcesses.splice(index, 1);
  62801. if (this._postProcesses.length > 0) {
  62802. this._postProcesses[0].autoClear = false;
  62803. }
  62804. };
  62805. RenderTargetTexture.prototype._shouldRender = function () {
  62806. if (this._currentRefreshId === -1) { // At least render once
  62807. this._currentRefreshId = 1;
  62808. return true;
  62809. }
  62810. if (this.refreshRate === this._currentRefreshId) {
  62811. this._currentRefreshId = 1;
  62812. return true;
  62813. }
  62814. this._currentRefreshId++;
  62815. return false;
  62816. };
  62817. RenderTargetTexture.prototype.getRenderSize = function () {
  62818. if (this._size.width) {
  62819. return this._size.width;
  62820. }
  62821. return this._size;
  62822. };
  62823. RenderTargetTexture.prototype.getRenderWidth = function () {
  62824. if (this._size.width) {
  62825. return this._size.width;
  62826. }
  62827. return this._size;
  62828. };
  62829. RenderTargetTexture.prototype.getRenderHeight = function () {
  62830. if (this._size.width) {
  62831. return this._size.height;
  62832. }
  62833. return this._size;
  62834. };
  62835. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62836. get: function () {
  62837. return true;
  62838. },
  62839. enumerable: true,
  62840. configurable: true
  62841. });
  62842. RenderTargetTexture.prototype.scale = function (ratio) {
  62843. var newSize = this.getRenderSize() * ratio;
  62844. this.resize(newSize);
  62845. };
  62846. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62847. if (this.isCube) {
  62848. return this._textureMatrix;
  62849. }
  62850. return _super.prototype.getReflectionTextureMatrix.call(this);
  62851. };
  62852. RenderTargetTexture.prototype.resize = function (size) {
  62853. this.releaseInternalTexture();
  62854. var scene = this.getScene();
  62855. if (!scene) {
  62856. return;
  62857. }
  62858. this._processSizeParameter(size);
  62859. if (this.isCube) {
  62860. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62861. }
  62862. else {
  62863. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62864. }
  62865. };
  62866. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62867. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62868. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62869. var scene = this.getScene();
  62870. if (!scene) {
  62871. return;
  62872. }
  62873. var engine = scene.getEngine();
  62874. if (this.useCameraPostProcesses !== undefined) {
  62875. useCameraPostProcess = this.useCameraPostProcesses;
  62876. }
  62877. if (this._waitingRenderList) {
  62878. this.renderList = [];
  62879. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62880. var id = this._waitingRenderList[index];
  62881. var mesh_1 = scene.getMeshByID(id);
  62882. if (mesh_1) {
  62883. this.renderList.push(mesh_1);
  62884. }
  62885. }
  62886. delete this._waitingRenderList;
  62887. }
  62888. // Is predicate defined?
  62889. if (this.renderListPredicate) {
  62890. if (this.renderList) {
  62891. this.renderList.splice(0); // Clear previous renderList
  62892. }
  62893. else {
  62894. this.renderList = [];
  62895. }
  62896. var scene = this.getScene();
  62897. if (!scene) {
  62898. return;
  62899. }
  62900. var sceneMeshes = scene.meshes;
  62901. for (var index = 0; index < sceneMeshes.length; index++) {
  62902. var mesh = sceneMeshes[index];
  62903. if (this.renderListPredicate(mesh)) {
  62904. this.renderList.push(mesh);
  62905. }
  62906. }
  62907. }
  62908. this.onBeforeBindObservable.notifyObservers(this);
  62909. // Set custom projection.
  62910. // Needs to be before binding to prevent changing the aspect ratio.
  62911. var camera;
  62912. if (this.activeCamera) {
  62913. camera = this.activeCamera;
  62914. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62915. if (this.activeCamera !== scene.activeCamera) {
  62916. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62917. }
  62918. }
  62919. else {
  62920. camera = scene.activeCamera;
  62921. if (camera) {
  62922. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62923. }
  62924. }
  62925. // Prepare renderingManager
  62926. this._renderingManager.reset();
  62927. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62928. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62929. var sceneRenderId = scene.getRenderId();
  62930. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62931. var mesh = currentRenderList[meshIndex];
  62932. if (mesh) {
  62933. if (!mesh.isReady(this.refreshRate === 0)) {
  62934. this.resetRefreshCounter();
  62935. continue;
  62936. }
  62937. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62938. var isMasked = void 0;
  62939. if (!this.renderList && camera) {
  62940. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62941. }
  62942. else {
  62943. isMasked = false;
  62944. }
  62945. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62946. mesh._activate(sceneRenderId);
  62947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62948. var subMesh = mesh.subMeshes[subIndex];
  62949. scene._activeIndices.addCount(subMesh.indexCount, false);
  62950. this._renderingManager.dispatch(subMesh, mesh);
  62951. }
  62952. }
  62953. }
  62954. }
  62955. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62956. var particleSystem = scene.particleSystems[particleIndex];
  62957. var emitter = particleSystem.emitter;
  62958. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62959. continue;
  62960. }
  62961. if (currentRenderList.indexOf(emitter) >= 0) {
  62962. this._renderingManager.dispatchParticles(particleSystem);
  62963. }
  62964. }
  62965. if (this.isCube) {
  62966. for (var face = 0; face < 6; face++) {
  62967. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62968. scene.incrementRenderId();
  62969. scene.resetCachedMaterial();
  62970. }
  62971. }
  62972. else {
  62973. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62974. }
  62975. this.onAfterUnbindObservable.notifyObservers(this);
  62976. if (scene.activeCamera) {
  62977. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62978. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62979. }
  62980. engine.setViewport(scene.activeCamera.viewport);
  62981. }
  62982. scene.resetCachedMaterial();
  62983. };
  62984. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62985. var minimum = 128;
  62986. var x = renderDimension * scale;
  62987. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62988. // Ensure we don't exceed the render dimension (while staying POT)
  62989. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62990. };
  62991. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62992. var _this = this;
  62993. if (!this._texture) {
  62994. return;
  62995. }
  62996. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62997. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62998. });
  62999. };
  63000. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63001. var scene = this.getScene();
  63002. if (!scene) {
  63003. return;
  63004. }
  63005. var engine = scene.getEngine();
  63006. if (!this._texture) {
  63007. return;
  63008. }
  63009. // Bind
  63010. if (this._postProcessManager) {
  63011. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63012. }
  63013. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63014. if (this._texture) {
  63015. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63016. }
  63017. }
  63018. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63019. // Clear
  63020. if (this.onClearObservable.hasObservers()) {
  63021. this.onClearObservable.notifyObservers(engine);
  63022. }
  63023. else {
  63024. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63025. }
  63026. if (!this._doNotChangeAspectRatio) {
  63027. scene.updateTransformMatrix(true);
  63028. }
  63029. // Render
  63030. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63031. if (this._postProcessManager) {
  63032. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63033. }
  63034. else if (useCameraPostProcess) {
  63035. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63036. }
  63037. if (!this._doNotChangeAspectRatio) {
  63038. scene.updateTransformMatrix(true);
  63039. }
  63040. // Dump ?
  63041. if (dumpForDebug) {
  63042. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63043. }
  63044. // Unbind
  63045. if (!this.isCube || faceIndex === 5) {
  63046. if (this.isCube) {
  63047. if (faceIndex === 5) {
  63048. engine.generateMipMapsForCubemap(this._texture);
  63049. }
  63050. }
  63051. this.unbindFrameBuffer(engine, faceIndex);
  63052. }
  63053. else {
  63054. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63055. }
  63056. };
  63057. /**
  63058. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63059. * This allowed control for front to back rendering or reversly depending of the special needs.
  63060. *
  63061. * @param renderingGroupId The rendering group id corresponding to its index
  63062. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63063. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63064. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63065. */
  63066. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63067. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63068. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63069. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63070. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63071. };
  63072. /**
  63073. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63074. *
  63075. * @param renderingGroupId The rendering group id corresponding to its index
  63076. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63077. */
  63078. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63079. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63080. };
  63081. RenderTargetTexture.prototype.clone = function () {
  63082. var textureSize = this.getSize();
  63083. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63084. // Base texture
  63085. newTexture.hasAlpha = this.hasAlpha;
  63086. newTexture.level = this.level;
  63087. // RenderTarget Texture
  63088. newTexture.coordinatesMode = this.coordinatesMode;
  63089. if (this.renderList) {
  63090. newTexture.renderList = this.renderList.slice(0);
  63091. }
  63092. return newTexture;
  63093. };
  63094. RenderTargetTexture.prototype.serialize = function () {
  63095. if (!this.name) {
  63096. return null;
  63097. }
  63098. var serializationObject = _super.prototype.serialize.call(this);
  63099. serializationObject.renderTargetSize = this.getRenderSize();
  63100. serializationObject.renderList = [];
  63101. if (this.renderList) {
  63102. for (var index = 0; index < this.renderList.length; index++) {
  63103. serializationObject.renderList.push(this.renderList[index].id);
  63104. }
  63105. }
  63106. return serializationObject;
  63107. };
  63108. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63109. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63110. var objBuffer = this.getInternalTexture();
  63111. var scene = this.getScene();
  63112. if (objBuffer && scene) {
  63113. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63114. }
  63115. };
  63116. RenderTargetTexture.prototype.dispose = function () {
  63117. if (this._postProcessManager) {
  63118. this._postProcessManager.dispose();
  63119. this._postProcessManager = null;
  63120. }
  63121. this.clearPostProcesses(true);
  63122. if (this._resizeObserver) {
  63123. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63124. this._resizeObserver = null;
  63125. }
  63126. this.renderList = null;
  63127. // Remove from custom render targets
  63128. var scene = this.getScene();
  63129. if (!scene) {
  63130. return;
  63131. }
  63132. var index = scene.customRenderTargets.indexOf(this);
  63133. if (index >= 0) {
  63134. scene.customRenderTargets.splice(index, 1);
  63135. }
  63136. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63137. var camera = _a[_i];
  63138. index = camera.customRenderTargets.indexOf(this);
  63139. if (index >= 0) {
  63140. camera.customRenderTargets.splice(index, 1);
  63141. }
  63142. }
  63143. _super.prototype.dispose.call(this);
  63144. };
  63145. RenderTargetTexture.prototype._rebuild = function () {
  63146. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63147. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63148. }
  63149. if (this._postProcessManager) {
  63150. this._postProcessManager._rebuild();
  63151. }
  63152. };
  63153. /**
  63154. * Clear the info related to rendering groups preventing retention point in material dispose.
  63155. */
  63156. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63157. if (this._renderingManager) {
  63158. this._renderingManager.freeRenderingGroups();
  63159. }
  63160. };
  63161. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63162. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63163. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63164. return RenderTargetTexture;
  63165. }(BABYLON.Texture));
  63166. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63167. })(BABYLON || (BABYLON = {}));
  63168. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63169. var BABYLON;
  63170. (function (BABYLON) {
  63171. ;
  63172. var MultiRenderTarget = /** @class */ (function (_super) {
  63173. __extends(MultiRenderTarget, _super);
  63174. function MultiRenderTarget(name, size, count, scene, options) {
  63175. var _this = this;
  63176. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63177. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63178. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63179. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63180. _this._engine = scene.getEngine();
  63181. if (!_this.isSupported) {
  63182. _this.dispose();
  63183. return;
  63184. }
  63185. var types = [];
  63186. var samplingModes = [];
  63187. for (var i = 0; i < count; i++) {
  63188. if (options && options.types && options.types[i] !== undefined) {
  63189. types.push(options.types[i]);
  63190. }
  63191. else {
  63192. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63193. }
  63194. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63195. samplingModes.push(options.samplingModes[i]);
  63196. }
  63197. else {
  63198. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63199. }
  63200. }
  63201. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63202. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63203. _this._size = size;
  63204. _this._multiRenderTargetOptions = {
  63205. samplingModes: samplingModes,
  63206. generateMipMaps: generateMipMaps,
  63207. generateDepthBuffer: generateDepthBuffer,
  63208. generateStencilBuffer: generateStencilBuffer,
  63209. generateDepthTexture: generateDepthTexture,
  63210. types: types,
  63211. textureCount: count
  63212. };
  63213. _this._createInternalTextures();
  63214. _this._createTextures();
  63215. return _this;
  63216. }
  63217. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63218. get: function () {
  63219. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63220. },
  63221. enumerable: true,
  63222. configurable: true
  63223. });
  63224. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63225. get: function () {
  63226. return this._textures;
  63227. },
  63228. enumerable: true,
  63229. configurable: true
  63230. });
  63231. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63232. get: function () {
  63233. return this._textures[this._textures.length - 1];
  63234. },
  63235. enumerable: true,
  63236. configurable: true
  63237. });
  63238. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63239. set: function (wrap) {
  63240. if (this._textures) {
  63241. for (var i = 0; i < this._textures.length; i++) {
  63242. this._textures[i].wrapU = wrap;
  63243. }
  63244. }
  63245. },
  63246. enumerable: true,
  63247. configurable: true
  63248. });
  63249. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63250. set: function (wrap) {
  63251. if (this._textures) {
  63252. for (var i = 0; i < this._textures.length; i++) {
  63253. this._textures[i].wrapV = wrap;
  63254. }
  63255. }
  63256. },
  63257. enumerable: true,
  63258. configurable: true
  63259. });
  63260. MultiRenderTarget.prototype._rebuild = function () {
  63261. this.releaseInternalTextures();
  63262. this._createInternalTextures();
  63263. for (var i = 0; i < this._internalTextures.length; i++) {
  63264. var texture = this._textures[i];
  63265. texture._texture = this._internalTextures[i];
  63266. }
  63267. // Keeps references to frame buffer and stencil/depth buffer
  63268. this._texture = this._internalTextures[0];
  63269. };
  63270. MultiRenderTarget.prototype._createInternalTextures = function () {
  63271. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63272. };
  63273. MultiRenderTarget.prototype._createTextures = function () {
  63274. this._textures = [];
  63275. for (var i = 0; i < this._internalTextures.length; i++) {
  63276. var texture = new BABYLON.Texture(null, this.getScene());
  63277. texture._texture = this._internalTextures[i];
  63278. this._textures.push(texture);
  63279. }
  63280. // Keeps references to frame buffer and stencil/depth buffer
  63281. this._texture = this._internalTextures[0];
  63282. };
  63283. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63284. get: function () {
  63285. return this._samples;
  63286. },
  63287. set: function (value) {
  63288. if (this._samples === value) {
  63289. return;
  63290. }
  63291. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. MultiRenderTarget.prototype.resize = function (size) {
  63297. this.releaseInternalTextures();
  63298. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63299. this._createInternalTextures();
  63300. };
  63301. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63302. var _this = this;
  63303. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63304. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63305. });
  63306. };
  63307. MultiRenderTarget.prototype.dispose = function () {
  63308. this.releaseInternalTextures();
  63309. _super.prototype.dispose.call(this);
  63310. };
  63311. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63312. if (!this._internalTextures) {
  63313. return;
  63314. }
  63315. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63316. if (this._internalTextures[i] !== undefined) {
  63317. this._internalTextures[i].dispose();
  63318. this._internalTextures.splice(i, 1);
  63319. }
  63320. }
  63321. };
  63322. return MultiRenderTarget;
  63323. }(BABYLON.RenderTargetTexture));
  63324. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63325. })(BABYLON || (BABYLON = {}));
  63326. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63327. var BABYLON;
  63328. (function (BABYLON) {
  63329. var MirrorTexture = /** @class */ (function (_super) {
  63330. __extends(MirrorTexture, _super);
  63331. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63332. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63334. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63335. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63336. _this.scene = scene;
  63337. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63338. _this._transformMatrix = BABYLON.Matrix.Zero();
  63339. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63340. _this._adaptiveBlurKernel = 0;
  63341. _this._blurKernelX = 0;
  63342. _this._blurKernelY = 0;
  63343. _this._blurRatio = 1.0;
  63344. _this.ignoreCameraViewport = true;
  63345. _this._updateGammaSpace();
  63346. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63347. _this._updateGammaSpace;
  63348. });
  63349. _this.onBeforeRenderObservable.add(function () {
  63350. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63351. _this._savedViewMatrix = scene.getViewMatrix();
  63352. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63353. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63354. scene.clipPlane = _this.mirrorPlane;
  63355. scene.getEngine().cullBackFaces = false;
  63356. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63357. });
  63358. _this.onAfterRenderObservable.add(function () {
  63359. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63360. scene.getEngine().cullBackFaces = true;
  63361. scene._mirroredCameraPosition = null;
  63362. delete scene.clipPlane;
  63363. });
  63364. return _this;
  63365. }
  63366. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63367. get: function () {
  63368. return this._blurRatio;
  63369. },
  63370. set: function (value) {
  63371. if (this._blurRatio === value) {
  63372. return;
  63373. }
  63374. this._blurRatio = value;
  63375. this._preparePostProcesses();
  63376. },
  63377. enumerable: true,
  63378. configurable: true
  63379. });
  63380. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63381. set: function (value) {
  63382. this._adaptiveBlurKernel = value;
  63383. this._autoComputeBlurKernel();
  63384. },
  63385. enumerable: true,
  63386. configurable: true
  63387. });
  63388. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63389. set: function (value) {
  63390. this.blurKernelX = value;
  63391. this.blurKernelY = value;
  63392. },
  63393. enumerable: true,
  63394. configurable: true
  63395. });
  63396. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63397. get: function () {
  63398. return this._blurKernelX;
  63399. },
  63400. set: function (value) {
  63401. if (this._blurKernelX === value) {
  63402. return;
  63403. }
  63404. this._blurKernelX = value;
  63405. this._preparePostProcesses();
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63411. get: function () {
  63412. return this._blurKernelY;
  63413. },
  63414. set: function (value) {
  63415. if (this._blurKernelY === value) {
  63416. return;
  63417. }
  63418. this._blurKernelY = value;
  63419. this._preparePostProcesses();
  63420. },
  63421. enumerable: true,
  63422. configurable: true
  63423. });
  63424. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63425. var engine = this.getScene().getEngine();
  63426. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63427. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63428. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63429. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63430. };
  63431. MirrorTexture.prototype._onRatioRescale = function () {
  63432. if (this._sizeRatio) {
  63433. this.resize(this._initialSizeParameter);
  63434. if (!this._adaptiveBlurKernel) {
  63435. this._preparePostProcesses();
  63436. }
  63437. }
  63438. if (this._adaptiveBlurKernel) {
  63439. this._autoComputeBlurKernel();
  63440. }
  63441. };
  63442. MirrorTexture.prototype._updateGammaSpace = function () {
  63443. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63444. };
  63445. MirrorTexture.prototype._preparePostProcesses = function () {
  63446. this.clearPostProcesses(true);
  63447. if (this._blurKernelX && this._blurKernelY) {
  63448. var engine = this.getScene().getEngine();
  63449. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63450. 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);
  63451. this._blurX.autoClear = false;
  63452. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63453. this._blurX.inputTexture = this._texture;
  63454. }
  63455. else {
  63456. this._blurX.alwaysForcePOT = true;
  63457. }
  63458. 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);
  63459. this._blurY.autoClear = false;
  63460. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63461. this.addPostProcess(this._blurX);
  63462. this.addPostProcess(this._blurY);
  63463. }
  63464. else {
  63465. if (this._blurY) {
  63466. this.removePostProcess(this._blurY);
  63467. this._blurY.dispose();
  63468. this._blurY = null;
  63469. }
  63470. if (this._blurX) {
  63471. this.removePostProcess(this._blurX);
  63472. this._blurX.dispose();
  63473. this._blurX = null;
  63474. }
  63475. }
  63476. };
  63477. MirrorTexture.prototype.clone = function () {
  63478. var scene = this.getScene();
  63479. if (!scene) {
  63480. return this;
  63481. }
  63482. var textureSize = this.getSize();
  63483. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63484. // Base texture
  63485. newTexture.hasAlpha = this.hasAlpha;
  63486. newTexture.level = this.level;
  63487. // Mirror Texture
  63488. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63489. if (this.renderList) {
  63490. newTexture.renderList = this.renderList.slice(0);
  63491. }
  63492. return newTexture;
  63493. };
  63494. MirrorTexture.prototype.serialize = function () {
  63495. if (!this.name) {
  63496. return null;
  63497. }
  63498. var serializationObject = _super.prototype.serialize.call(this);
  63499. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63500. return serializationObject;
  63501. };
  63502. MirrorTexture.prototype.dispose = function () {
  63503. _super.prototype.dispose.call(this);
  63504. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63505. };
  63506. return MirrorTexture;
  63507. }(BABYLON.RenderTargetTexture));
  63508. BABYLON.MirrorTexture = MirrorTexture;
  63509. })(BABYLON || (BABYLON = {}));
  63510. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63511. var BABYLON;
  63512. (function (BABYLON) {
  63513. /**
  63514. * Creates a refraction texture used by refraction channel of the standard material.
  63515. * @param name the texture name
  63516. * @param size size of the underlying texture
  63517. * @param scene root scene
  63518. */
  63519. var RefractionTexture = /** @class */ (function (_super) {
  63520. __extends(RefractionTexture, _super);
  63521. function RefractionTexture(name, size, scene, generateMipMaps) {
  63522. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63523. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63524. _this.depth = 2.0;
  63525. _this.onBeforeRenderObservable.add(function () {
  63526. scene.clipPlane = _this.refractionPlane;
  63527. });
  63528. _this.onAfterRenderObservable.add(function () {
  63529. delete scene.clipPlane;
  63530. });
  63531. return _this;
  63532. }
  63533. RefractionTexture.prototype.clone = function () {
  63534. var scene = this.getScene();
  63535. if (!scene) {
  63536. return this;
  63537. }
  63538. var textureSize = this.getSize();
  63539. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63540. // Base texture
  63541. newTexture.hasAlpha = this.hasAlpha;
  63542. newTexture.level = this.level;
  63543. // Refraction Texture
  63544. newTexture.refractionPlane = this.refractionPlane.clone();
  63545. if (this.renderList) {
  63546. newTexture.renderList = this.renderList.slice(0);
  63547. }
  63548. newTexture.depth = this.depth;
  63549. return newTexture;
  63550. };
  63551. RefractionTexture.prototype.serialize = function () {
  63552. if (!this.name) {
  63553. return null;
  63554. }
  63555. var serializationObject = _super.prototype.serialize.call(this);
  63556. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63557. serializationObject.depth = this.depth;
  63558. return serializationObject;
  63559. };
  63560. return RefractionTexture;
  63561. }(BABYLON.RenderTargetTexture));
  63562. BABYLON.RefractionTexture = RefractionTexture;
  63563. })(BABYLON || (BABYLON = {}));
  63564. //# sourceMappingURL=babylon.refractionTexture.js.map
  63565. var BABYLON;
  63566. (function (BABYLON) {
  63567. /**
  63568. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63569. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63570. */
  63571. var DynamicTexture = /** @class */ (function (_super) {
  63572. __extends(DynamicTexture, _super);
  63573. /**
  63574. * Creates a {BABYLON.DynamicTexture}
  63575. * @param name defines the name of the texture
  63576. * @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
  63577. * @param scene defines the scene where you want the texture
  63578. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63579. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63580. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63581. */
  63582. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63583. if (scene === void 0) { scene = null; }
  63584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63585. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63586. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63587. _this.name = name;
  63588. _this._engine = _this.getScene().getEngine();
  63589. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63590. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63591. _this._generateMipMaps = generateMipMaps;
  63592. if (options.getContext) {
  63593. _this._canvas = options;
  63594. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63595. }
  63596. else {
  63597. _this._canvas = document.createElement("canvas");
  63598. if (options.width) {
  63599. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63600. }
  63601. else {
  63602. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63603. }
  63604. }
  63605. var textureSize = _this.getSize();
  63606. _this._canvas.width = textureSize.width;
  63607. _this._canvas.height = textureSize.height;
  63608. _this._context = _this._canvas.getContext("2d");
  63609. return _this;
  63610. }
  63611. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63612. /**
  63613. * Gets the current state of canRescale
  63614. */
  63615. get: function () {
  63616. return true;
  63617. },
  63618. enumerable: true,
  63619. configurable: true
  63620. });
  63621. DynamicTexture.prototype._recreate = function (textureSize) {
  63622. this._canvas.width = textureSize.width;
  63623. this._canvas.height = textureSize.height;
  63624. this.releaseInternalTexture();
  63625. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63626. };
  63627. /**
  63628. * Scales the texture
  63629. * @param ratio the scale factor to apply to both width and height
  63630. */
  63631. DynamicTexture.prototype.scale = function (ratio) {
  63632. var textureSize = this.getSize();
  63633. textureSize.width *= ratio;
  63634. textureSize.height *= ratio;
  63635. this._recreate(textureSize);
  63636. };
  63637. /**
  63638. * Resizes the texture
  63639. * @param width the new width
  63640. * @param height the new height
  63641. */
  63642. DynamicTexture.prototype.scaleTo = function (width, height) {
  63643. var textureSize = this.getSize();
  63644. textureSize.width = width;
  63645. textureSize.height = height;
  63646. this._recreate(textureSize);
  63647. };
  63648. /**
  63649. * Gets the context of the canvas used by the texture
  63650. * @returns the canvas context of the dynamic texture
  63651. */
  63652. DynamicTexture.prototype.getContext = function () {
  63653. return this._context;
  63654. };
  63655. /**
  63656. * Clears the texture
  63657. */
  63658. DynamicTexture.prototype.clear = function () {
  63659. var size = this.getSize();
  63660. this._context.fillRect(0, 0, size.width, size.height);
  63661. };
  63662. /**
  63663. * Updates the texture
  63664. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63665. */
  63666. DynamicTexture.prototype.update = function (invertY) {
  63667. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63668. };
  63669. /**
  63670. * Draws text onto the texture
  63671. * @param text defines the text to be drawn
  63672. * @param x defines the placement of the text from the left
  63673. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63674. * @param font defines the font to be used with font-style, font-size, font-name
  63675. * @param color defines the color used for the text
  63676. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63677. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63678. * @param update defines whether texture is immediately update (default is true)
  63679. */
  63680. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63681. if (update === void 0) { update = true; }
  63682. var size = this.getSize();
  63683. if (clearColor) {
  63684. this._context.fillStyle = clearColor;
  63685. this._context.fillRect(0, 0, size.width, size.height);
  63686. }
  63687. this._context.font = font;
  63688. if (x === null || x === undefined) {
  63689. var textSize = this._context.measureText(text);
  63690. x = (size.width - textSize.width) / 2;
  63691. }
  63692. if (y === null || y === undefined) {
  63693. var fontSize = parseInt((font.replace(/\D/g, '')));
  63694. ;
  63695. y = (size.height / 2) + (fontSize / 3.65);
  63696. }
  63697. this._context.fillStyle = color;
  63698. this._context.fillText(text, x, y);
  63699. if (update) {
  63700. this.update(invertY);
  63701. }
  63702. };
  63703. /**
  63704. * Clones the texture
  63705. * @returns the clone of the texture.
  63706. */
  63707. DynamicTexture.prototype.clone = function () {
  63708. var scene = this.getScene();
  63709. if (!scene) {
  63710. return this;
  63711. }
  63712. var textureSize = this.getSize();
  63713. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63714. // Base texture
  63715. newTexture.hasAlpha = this.hasAlpha;
  63716. newTexture.level = this.level;
  63717. // Dynamic Texture
  63718. newTexture.wrapU = this.wrapU;
  63719. newTexture.wrapV = this.wrapV;
  63720. return newTexture;
  63721. };
  63722. /** @ignore */
  63723. DynamicTexture.prototype._rebuild = function () {
  63724. this.update();
  63725. };
  63726. return DynamicTexture;
  63727. }(BABYLON.Texture));
  63728. BABYLON.DynamicTexture = DynamicTexture;
  63729. })(BABYLON || (BABYLON = {}));
  63730. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63731. var BABYLON;
  63732. (function (BABYLON) {
  63733. var VideoTexture = /** @class */ (function (_super) {
  63734. __extends(VideoTexture, _super);
  63735. /**
  63736. * Creates a video texture.
  63737. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63738. * @param {string | null} name optional name, will detect from video source, if not defined
  63739. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63740. * @param {BABYLON.Scene} scene is obviously the current scene.
  63741. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63742. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63743. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63744. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63745. */
  63746. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63747. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63748. if (invertY === void 0) { invertY = false; }
  63749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63750. if (settings === void 0) { settings = {
  63751. autoPlay: true,
  63752. loop: true,
  63753. autoUpdateTexture: true,
  63754. }; }
  63755. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63756. _this._createInternalTexture = function () {
  63757. if (_this._texture != null) {
  63758. return;
  63759. }
  63760. if (!_this._engine.needPOTTextures ||
  63761. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63762. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63763. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63764. }
  63765. else {
  63766. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63767. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63768. _this._generateMipMaps = false;
  63769. }
  63770. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63771. _this._texture.isReady = true;
  63772. _this._updateInternalTexture();
  63773. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63774. _this.onLoadObservable.notifyObservers(_this);
  63775. }
  63776. };
  63777. _this.reset = function () {
  63778. if (_this._texture == null) {
  63779. return;
  63780. }
  63781. _this._texture.dispose();
  63782. _this._texture = null;
  63783. };
  63784. _this._updateInternalTexture = function (e) {
  63785. if (_this._texture == null || !_this._texture.isReady) {
  63786. return;
  63787. }
  63788. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63789. return;
  63790. }
  63791. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63792. };
  63793. _this._engine = _this.getScene().getEngine();
  63794. _this._generateMipMaps = generateMipMaps;
  63795. _this._samplingMode = samplingMode;
  63796. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63797. _this.name = name || _this._getName(src);
  63798. _this.video = _this._getVideo(src);
  63799. if (settings.autoPlay !== undefined) {
  63800. _this.video.autoplay = settings.autoPlay;
  63801. }
  63802. if (settings.loop !== undefined) {
  63803. _this.video.loop = settings.loop;
  63804. }
  63805. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63806. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63807. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63808. _this.video.addEventListener("emptied", _this.reset);
  63809. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63810. _this._createInternalTexture();
  63811. }
  63812. return _this;
  63813. }
  63814. VideoTexture.prototype._getName = function (src) {
  63815. if (src instanceof HTMLVideoElement) {
  63816. return src.currentSrc;
  63817. }
  63818. if (typeof src === "object") {
  63819. return src.toString();
  63820. }
  63821. return src;
  63822. };
  63823. ;
  63824. VideoTexture.prototype._getVideo = function (src) {
  63825. if (src instanceof HTMLVideoElement) {
  63826. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63827. return src;
  63828. }
  63829. var video = document.createElement("video");
  63830. if (typeof src === "string") {
  63831. BABYLON.Tools.SetCorsBehavior(src, video);
  63832. video.src = src;
  63833. }
  63834. else {
  63835. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63836. src.forEach(function (url) {
  63837. var source = document.createElement("source");
  63838. source.src = url;
  63839. video.appendChild(source);
  63840. });
  63841. }
  63842. return video;
  63843. };
  63844. ;
  63845. /**
  63846. * Internal method to initiate `update`.
  63847. */
  63848. VideoTexture.prototype._rebuild = function () {
  63849. this.update();
  63850. };
  63851. /**
  63852. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63853. */
  63854. VideoTexture.prototype.update = function () {
  63855. if (!this.autoUpdateTexture) {
  63856. // Expecting user to call `updateTexture` manually
  63857. return;
  63858. }
  63859. this.updateTexture(true);
  63860. };
  63861. /**
  63862. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63863. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63864. */
  63865. VideoTexture.prototype.updateTexture = function (isVisible) {
  63866. if (!isVisible) {
  63867. return;
  63868. }
  63869. if (this.video.paused) {
  63870. return;
  63871. }
  63872. this._updateInternalTexture();
  63873. };
  63874. /**
  63875. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63876. * @param url New url.
  63877. */
  63878. VideoTexture.prototype.updateURL = function (url) {
  63879. this.video.src = url;
  63880. };
  63881. VideoTexture.prototype.dispose = function () {
  63882. _super.prototype.dispose.call(this);
  63883. this.video.removeEventListener("canplay", this._createInternalTexture);
  63884. this.video.removeEventListener("paused", this._updateInternalTexture);
  63885. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63886. this.video.removeEventListener("emptied", this.reset);
  63887. this.video.pause();
  63888. };
  63889. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63890. var video = document.createElement("video");
  63891. var constraintsDeviceId;
  63892. if (constraints && constraints.deviceId) {
  63893. constraintsDeviceId = {
  63894. exact: constraints.deviceId,
  63895. };
  63896. }
  63897. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63898. if (navigator.mediaDevices) {
  63899. navigator.mediaDevices.getUserMedia({ video: constraints })
  63900. .then(function (stream) {
  63901. if (video.mozSrcObject !== undefined) {
  63902. // hack for Firefox < 19
  63903. video.mozSrcObject = stream;
  63904. }
  63905. else {
  63906. video.srcObject = stream;
  63907. }
  63908. var onPlaying = function () {
  63909. if (onReady) {
  63910. onReady(new VideoTexture("video", video, scene, true, true));
  63911. }
  63912. video.removeEventListener("playing", onPlaying);
  63913. };
  63914. video.addEventListener("playing", onPlaying);
  63915. video.play();
  63916. })
  63917. .catch(function (err) {
  63918. BABYLON.Tools.Error(err.name);
  63919. });
  63920. }
  63921. else {
  63922. navigator.getUserMedia =
  63923. navigator.getUserMedia ||
  63924. navigator.webkitGetUserMedia ||
  63925. navigator.mozGetUserMedia ||
  63926. navigator.msGetUserMedia;
  63927. if (navigator.getUserMedia) {
  63928. navigator.getUserMedia({
  63929. video: {
  63930. deviceId: constraintsDeviceId,
  63931. width: {
  63932. min: (constraints && constraints.minWidth) || 256,
  63933. max: (constraints && constraints.maxWidth) || 640,
  63934. },
  63935. height: {
  63936. min: (constraints && constraints.minHeight) || 256,
  63937. max: (constraints && constraints.maxHeight) || 480,
  63938. },
  63939. },
  63940. }, function (stream) {
  63941. if (video.mozSrcObject !== undefined) {
  63942. // hack for Firefox < 19
  63943. video.mozSrcObject = stream;
  63944. }
  63945. else {
  63946. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63947. }
  63948. video.play();
  63949. if (onReady) {
  63950. onReady(new VideoTexture("video", video, scene, true, true));
  63951. }
  63952. }, function (e) {
  63953. BABYLON.Tools.Error(e.name);
  63954. });
  63955. }
  63956. }
  63957. };
  63958. return VideoTexture;
  63959. }(BABYLON.Texture));
  63960. BABYLON.VideoTexture = VideoTexture;
  63961. })(BABYLON || (BABYLON = {}));
  63962. //# sourceMappingURL=babylon.videoTexture.js.map
  63963. var BABYLON;
  63964. (function (BABYLON) {
  63965. var RawTexture = /** @class */ (function (_super) {
  63966. __extends(RawTexture, _super);
  63967. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63968. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63969. if (invertY === void 0) { invertY = false; }
  63970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63971. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63972. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63973. _this.format = format;
  63974. _this._engine = scene.getEngine();
  63975. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63976. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63977. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63978. return _this;
  63979. }
  63980. RawTexture.prototype.update = function (data) {
  63981. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63982. };
  63983. // Statics
  63984. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63986. if (invertY === void 0) { invertY = false; }
  63987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63988. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63989. };
  63990. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63992. if (invertY === void 0) { invertY = false; }
  63993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63994. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63995. };
  63996. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63997. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63998. if (invertY === void 0) { invertY = false; }
  63999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64001. };
  64002. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64004. if (invertY === void 0) { invertY = false; }
  64005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64006. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64007. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64008. };
  64009. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64011. if (invertY === void 0) { invertY = false; }
  64012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64013. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64015. };
  64016. return RawTexture;
  64017. }(BABYLON.Texture));
  64018. BABYLON.RawTexture = RawTexture;
  64019. })(BABYLON || (BABYLON = {}));
  64020. //# sourceMappingURL=babylon.rawTexture.js.map
  64021. var BABYLON;
  64022. (function (BABYLON) {
  64023. /**
  64024. * Class used to store 3D textures containing user data
  64025. */
  64026. var RawTexture3D = /** @class */ (function (_super) {
  64027. __extends(RawTexture3D, _super);
  64028. /**
  64029. * Create a new RawTexture3D
  64030. * @param data defines the data of the texture
  64031. * @param width defines the width of the texture
  64032. * @param height defines the height of the texture
  64033. * @param depth defines the depth of the texture
  64034. * @param format defines the texture format to use
  64035. * @param scene defines the hosting scene
  64036. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64037. * @param invertY defines if texture must be stored with Y axis inverted
  64038. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64039. */
  64040. function RawTexture3D(data, width, height, depth,
  64041. /** Gets or sets the texture format to use*/
  64042. format, scene, generateMipMaps, invertY, samplingMode) {
  64043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64044. if (invertY === void 0) { invertY = false; }
  64045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64046. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64047. _this.format = format;
  64048. _this._engine = scene.getEngine();
  64049. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64050. _this.is3D = true;
  64051. return _this;
  64052. }
  64053. /**
  64054. * Update the texture with new data
  64055. * @param data defines the data to store in the texture
  64056. */
  64057. RawTexture3D.prototype.update = function (data) {
  64058. if (!this._texture) {
  64059. return;
  64060. }
  64061. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64062. };
  64063. return RawTexture3D;
  64064. }(BABYLON.Texture));
  64065. BABYLON.RawTexture3D = RawTexture3D;
  64066. })(BABYLON || (BABYLON = {}));
  64067. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64068. var BABYLON;
  64069. (function (BABYLON) {
  64070. /**
  64071. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64072. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64073. */
  64074. var PostProcess = /** @class */ (function () {
  64075. /**
  64076. * Creates a new instance PostProcess
  64077. * @param name The name of the PostProcess.
  64078. * @param fragmentUrl The url of the fragment shader to be used.
  64079. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64080. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64081. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64082. * @param camera The camera to apply the render pass to.
  64083. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64084. * @param engine The engine which the post process will be applied. (default: current engine)
  64085. * @param reusable If the post process can be reused on the same frame. (default: false)
  64086. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64087. * @param textureType Type of textures used when performing the post process. (default: 0)
  64088. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64089. * @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
  64090. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64091. */
  64092. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64094. if (defines === void 0) { defines = null; }
  64095. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64096. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64097. if (blockCompilation === void 0) { blockCompilation = false; }
  64098. this.name = name;
  64099. /**
  64100. * Width of the texture to apply the post process on
  64101. */
  64102. this.width = -1;
  64103. /**
  64104. * Height of the texture to apply the post process on
  64105. */
  64106. this.height = -1;
  64107. /**
  64108. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64109. */
  64110. this._outputTexture = null;
  64111. /**
  64112. * If the buffer needs to be cleared before applying the post process. (default: true)
  64113. * Should be set to false if shader will overwrite all previous pixels.
  64114. */
  64115. this.autoClear = true;
  64116. /**
  64117. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64118. */
  64119. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64120. /**
  64121. * Animations to be used for the post processing
  64122. */
  64123. this.animations = new Array();
  64124. /**
  64125. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64126. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64127. */
  64128. this.enablePixelPerfectMode = false;
  64129. /**
  64130. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64131. */
  64132. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64133. /**
  64134. * Force textures to be a power of two (default: false)
  64135. */
  64136. this.alwaysForcePOT = false;
  64137. /**
  64138. * Number of sample textures (default: 1)
  64139. */
  64140. this.samples = 1;
  64141. /**
  64142. * Modify the scale of the post process to be the same as the viewport (default: false)
  64143. */
  64144. this.adaptScaleToCurrentViewport = false;
  64145. this._reusable = false;
  64146. /**
  64147. * Smart array of input and output textures for the post process.
  64148. */
  64149. this._textures = new BABYLON.SmartArray(2);
  64150. /**
  64151. * The index in _textures that corresponds to the output texture.
  64152. */
  64153. this._currentRenderTextureInd = 0;
  64154. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64155. this._texelSize = BABYLON.Vector2.Zero();
  64156. // Events
  64157. /**
  64158. * An event triggered when the postprocess is activated.
  64159. */
  64160. this.onActivateObservable = new BABYLON.Observable();
  64161. /**
  64162. * An event triggered when the postprocess changes its size.
  64163. */
  64164. this.onSizeChangedObservable = new BABYLON.Observable();
  64165. /**
  64166. * An event triggered when the postprocess applies its effect.
  64167. */
  64168. this.onApplyObservable = new BABYLON.Observable();
  64169. /**
  64170. * An event triggered before rendering the postprocess
  64171. */
  64172. this.onBeforeRenderObservable = new BABYLON.Observable();
  64173. /**
  64174. * An event triggered after rendering the postprocess
  64175. */
  64176. this.onAfterRenderObservable = new BABYLON.Observable();
  64177. if (camera != null) {
  64178. this._camera = camera;
  64179. this._scene = camera.getScene();
  64180. camera.attachPostProcess(this);
  64181. this._engine = this._scene.getEngine();
  64182. this._scene.postProcesses.push(this);
  64183. }
  64184. else if (engine) {
  64185. this._engine = engine;
  64186. this._engine.postProcesses.push(this);
  64187. }
  64188. this._options = options;
  64189. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64190. this._reusable = reusable || false;
  64191. this._textureType = textureType;
  64192. this._samplers = samplers || [];
  64193. this._samplers.push("textureSampler");
  64194. this._fragmentUrl = fragmentUrl;
  64195. this._vertexUrl = vertexUrl;
  64196. this._parameters = parameters || [];
  64197. this._parameters.push("scale");
  64198. this._indexParameters = indexParameters;
  64199. if (!blockCompilation) {
  64200. this.updateEffect(defines);
  64201. }
  64202. }
  64203. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64204. /**
  64205. * A function that is added to the onActivateObservable
  64206. */
  64207. set: function (callback) {
  64208. if (this._onActivateObserver) {
  64209. this.onActivateObservable.remove(this._onActivateObserver);
  64210. }
  64211. if (callback) {
  64212. this._onActivateObserver = this.onActivateObservable.add(callback);
  64213. }
  64214. },
  64215. enumerable: true,
  64216. configurable: true
  64217. });
  64218. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64219. /**
  64220. * A function that is added to the onSizeChangedObservable
  64221. */
  64222. set: function (callback) {
  64223. if (this._onSizeChangedObserver) {
  64224. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64225. }
  64226. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64227. },
  64228. enumerable: true,
  64229. configurable: true
  64230. });
  64231. Object.defineProperty(PostProcess.prototype, "onApply", {
  64232. /**
  64233. * A function that is added to the onApplyObservable
  64234. */
  64235. set: function (callback) {
  64236. if (this._onApplyObserver) {
  64237. this.onApplyObservable.remove(this._onApplyObserver);
  64238. }
  64239. this._onApplyObserver = this.onApplyObservable.add(callback);
  64240. },
  64241. enumerable: true,
  64242. configurable: true
  64243. });
  64244. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64245. /**
  64246. * A function that is added to the onBeforeRenderObservable
  64247. */
  64248. set: function (callback) {
  64249. if (this._onBeforeRenderObserver) {
  64250. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64251. }
  64252. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64253. },
  64254. enumerable: true,
  64255. configurable: true
  64256. });
  64257. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64258. /**
  64259. * A function that is added to the onAfterRenderObservable
  64260. */
  64261. set: function (callback) {
  64262. if (this._onAfterRenderObserver) {
  64263. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64264. }
  64265. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64266. },
  64267. enumerable: true,
  64268. configurable: true
  64269. });
  64270. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64271. /**
  64272. * 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
  64273. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64274. */
  64275. get: function () {
  64276. return this._textures.data[this._currentRenderTextureInd];
  64277. },
  64278. set: function (value) {
  64279. this._forcedOutputTexture = value;
  64280. },
  64281. enumerable: true,
  64282. configurable: true
  64283. });
  64284. /**
  64285. * Gets the camera which post process is applied to.
  64286. * @returns The camera the post process is applied to.
  64287. */
  64288. PostProcess.prototype.getCamera = function () {
  64289. return this._camera;
  64290. };
  64291. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64292. /**
  64293. * Gets the texel size of the postprocess.
  64294. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64295. */
  64296. get: function () {
  64297. if (this._shareOutputWithPostProcess) {
  64298. return this._shareOutputWithPostProcess.texelSize;
  64299. }
  64300. if (this._forcedOutputTexture) {
  64301. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64302. }
  64303. return this._texelSize;
  64304. },
  64305. enumerable: true,
  64306. configurable: true
  64307. });
  64308. /**
  64309. * Gets the engine which this post process belongs to.
  64310. * @returns The engine the post process was enabled with.
  64311. */
  64312. PostProcess.prototype.getEngine = function () {
  64313. return this._engine;
  64314. };
  64315. /**
  64316. * The effect that is created when initializing the post process.
  64317. * @returns The created effect corrisponding the the postprocess.
  64318. */
  64319. PostProcess.prototype.getEffect = function () {
  64320. return this._effect;
  64321. };
  64322. /**
  64323. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64324. * @param postProcess The post process to share the output with.
  64325. * @returns This post process.
  64326. */
  64327. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64328. this._disposeTextures();
  64329. this._shareOutputWithPostProcess = postProcess;
  64330. return this;
  64331. };
  64332. /**
  64333. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64334. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64335. */
  64336. PostProcess.prototype.useOwnOutput = function () {
  64337. if (this._textures.length == 0) {
  64338. this._textures = new BABYLON.SmartArray(2);
  64339. }
  64340. this._shareOutputWithPostProcess = null;
  64341. };
  64342. /**
  64343. * Updates the effect with the current post process compile time values and recompiles the shader.
  64344. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64345. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64346. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64347. * @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
  64348. * @param onCompiled Called when the shader has been compiled.
  64349. * @param onError Called if there is an error when compiling a shader.
  64350. */
  64351. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64352. if (defines === void 0) { defines = null; }
  64353. if (uniforms === void 0) { uniforms = null; }
  64354. if (samplers === void 0) { samplers = null; }
  64355. 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);
  64356. };
  64357. /**
  64358. * The post process is reusable if it can be used multiple times within one frame.
  64359. * @returns If the post process is reusable
  64360. */
  64361. PostProcess.prototype.isReusable = function () {
  64362. return this._reusable;
  64363. };
  64364. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64365. PostProcess.prototype.markTextureDirty = function () {
  64366. this.width = -1;
  64367. };
  64368. /**
  64369. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64370. * 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.
  64371. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64372. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64373. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64374. * @returns The target texture that was bound to be written to.
  64375. */
  64376. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64377. var _this = this;
  64378. if (sourceTexture === void 0) { sourceTexture = null; }
  64379. camera = camera || this._camera;
  64380. var scene = camera.getScene();
  64381. var engine = scene.getEngine();
  64382. var maxSize = engine.getCaps().maxTextureSize;
  64383. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64384. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64385. // 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
  64386. var webVRCamera = camera.parent;
  64387. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64388. requiredWidth /= 2;
  64389. }
  64390. var desiredWidth = (this._options.width || requiredWidth);
  64391. var desiredHeight = this._options.height || requiredHeight;
  64392. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64393. if (this.adaptScaleToCurrentViewport) {
  64394. var currentViewport = engine.currentViewport;
  64395. if (currentViewport) {
  64396. desiredWidth *= currentViewport.width;
  64397. desiredHeight *= currentViewport.height;
  64398. }
  64399. }
  64400. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64401. if (!this._options.width) {
  64402. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64403. }
  64404. if (!this._options.height) {
  64405. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64406. }
  64407. }
  64408. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64409. if (this._textures.length > 0) {
  64410. for (var i = 0; i < this._textures.length; i++) {
  64411. this._engine._releaseTexture(this._textures.data[i]);
  64412. }
  64413. this._textures.reset();
  64414. }
  64415. this.width = desiredWidth;
  64416. this.height = desiredHeight;
  64417. var textureSize = { width: this.width, height: this.height };
  64418. var textureOptions = {
  64419. generateMipMaps: false,
  64420. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64421. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64422. samplingMode: this.renderTargetSamplingMode,
  64423. type: this._textureType
  64424. };
  64425. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64426. if (this._reusable) {
  64427. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64428. }
  64429. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64430. this.onSizeChangedObservable.notifyObservers(this);
  64431. }
  64432. this._textures.forEach(function (texture) {
  64433. if (texture.samples !== _this.samples) {
  64434. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64435. }
  64436. });
  64437. }
  64438. var target;
  64439. if (this._shareOutputWithPostProcess) {
  64440. target = this._shareOutputWithPostProcess.inputTexture;
  64441. }
  64442. else if (this._forcedOutputTexture) {
  64443. target = this._forcedOutputTexture;
  64444. this.width = this._forcedOutputTexture.width;
  64445. this.height = this._forcedOutputTexture.height;
  64446. }
  64447. else {
  64448. target = this.inputTexture;
  64449. }
  64450. // Bind the input of this post process to be used as the output of the previous post process.
  64451. if (this.enablePixelPerfectMode) {
  64452. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64453. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64454. }
  64455. else {
  64456. this._scaleRatio.copyFromFloats(1, 1);
  64457. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64458. }
  64459. this.onActivateObservable.notifyObservers(camera);
  64460. // Clear
  64461. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64462. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64463. }
  64464. if (this._reusable) {
  64465. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64466. }
  64467. return target;
  64468. };
  64469. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64470. /**
  64471. * If the post process is supported.
  64472. */
  64473. get: function () {
  64474. return this._effect.isSupported;
  64475. },
  64476. enumerable: true,
  64477. configurable: true
  64478. });
  64479. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64480. /**
  64481. * The aspect ratio of the output texture.
  64482. */
  64483. get: function () {
  64484. if (this._shareOutputWithPostProcess) {
  64485. return this._shareOutputWithPostProcess.aspectRatio;
  64486. }
  64487. if (this._forcedOutputTexture) {
  64488. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64489. }
  64490. return this.width / this.height;
  64491. },
  64492. enumerable: true,
  64493. configurable: true
  64494. });
  64495. /**
  64496. * Get a value indicating if the post-process is ready to be used
  64497. * @returns true if the post-process is ready (shader is compiled)
  64498. */
  64499. PostProcess.prototype.isReady = function () {
  64500. return this._effect && this._effect.isReady();
  64501. };
  64502. /**
  64503. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64504. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64505. */
  64506. PostProcess.prototype.apply = function () {
  64507. // Check
  64508. if (!this._effect || !this._effect.isReady())
  64509. return null;
  64510. // States
  64511. this._engine.enableEffect(this._effect);
  64512. this._engine.setState(false);
  64513. this._engine.setDepthBuffer(false);
  64514. this._engine.setDepthWrite(false);
  64515. // Alpha
  64516. this._engine.setAlphaMode(this.alphaMode);
  64517. if (this.alphaConstants) {
  64518. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64519. }
  64520. // Bind the output texture of the preivous post process as the input to this post process.
  64521. var source;
  64522. if (this._shareOutputWithPostProcess) {
  64523. source = this._shareOutputWithPostProcess.inputTexture;
  64524. }
  64525. else if (this._forcedOutputTexture) {
  64526. source = this._forcedOutputTexture;
  64527. }
  64528. else {
  64529. source = this.inputTexture;
  64530. }
  64531. this._effect._bindTexture("textureSampler", source);
  64532. // Parameters
  64533. this._effect.setVector2("scale", this._scaleRatio);
  64534. this.onApplyObservable.notifyObservers(this._effect);
  64535. return this._effect;
  64536. };
  64537. PostProcess.prototype._disposeTextures = function () {
  64538. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64539. return;
  64540. }
  64541. if (this._textures.length > 0) {
  64542. for (var i = 0; i < this._textures.length; i++) {
  64543. this._engine._releaseTexture(this._textures.data[i]);
  64544. }
  64545. }
  64546. this._textures.dispose();
  64547. };
  64548. /**
  64549. * Disposes the post process.
  64550. * @param camera The camera to dispose the post process on.
  64551. */
  64552. PostProcess.prototype.dispose = function (camera) {
  64553. camera = camera || this._camera;
  64554. this._disposeTextures();
  64555. if (this._scene) {
  64556. var index_1 = this._scene.postProcesses.indexOf(this);
  64557. if (index_1 !== -1) {
  64558. this._scene.postProcesses.splice(index_1, 1);
  64559. }
  64560. }
  64561. else {
  64562. var index_2 = this._engine.postProcesses.indexOf(this);
  64563. if (index_2 !== -1) {
  64564. this._engine.postProcesses.splice(index_2, 1);
  64565. }
  64566. }
  64567. if (!camera) {
  64568. return;
  64569. }
  64570. camera.detachPostProcess(this);
  64571. var index = camera._postProcesses.indexOf(this);
  64572. if (index === 0 && camera._postProcesses.length > 0) {
  64573. var firstPostProcess = this._camera._getFirstPostProcess();
  64574. if (firstPostProcess) {
  64575. firstPostProcess.markTextureDirty();
  64576. }
  64577. }
  64578. this.onActivateObservable.clear();
  64579. this.onAfterRenderObservable.clear();
  64580. this.onApplyObservable.clear();
  64581. this.onBeforeRenderObservable.clear();
  64582. this.onSizeChangedObservable.clear();
  64583. };
  64584. return PostProcess;
  64585. }());
  64586. BABYLON.PostProcess = PostProcess;
  64587. })(BABYLON || (BABYLON = {}));
  64588. //# sourceMappingURL=babylon.postProcess.js.map
  64589. var BABYLON;
  64590. (function (BABYLON) {
  64591. var PassPostProcess = /** @class */ (function (_super) {
  64592. __extends(PassPostProcess, _super);
  64593. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64594. if (camera === void 0) { camera = null; }
  64595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64596. if (blockCompilation === void 0) { blockCompilation = false; }
  64597. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64598. }
  64599. return PassPostProcess;
  64600. }(BABYLON.PostProcess));
  64601. BABYLON.PassPostProcess = PassPostProcess;
  64602. })(BABYLON || (BABYLON = {}));
  64603. //# sourceMappingURL=babylon.passPostProcess.js.map
  64604. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64605. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64606. s = arguments[i];
  64607. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64608. t[p] = s[p];
  64609. }
  64610. return t;
  64611. };
  64612. var BABYLON;
  64613. (function (BABYLON) {
  64614. /**
  64615. * Default implementation IShadowGenerator.
  64616. * This is the main object responsible of generating shadows in the framework.
  64617. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64618. */
  64619. var ShadowGenerator = /** @class */ (function () {
  64620. /**
  64621. * Creates a ShadowGenerator object.
  64622. * A ShadowGenerator is the required tool to use the shadows.
  64623. * Each light casting shadows needs to use its own ShadowGenerator.
  64624. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64625. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64626. * @param light The light object generating the shadows.
  64627. * @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.
  64628. */
  64629. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64630. this._bias = 0.00005;
  64631. this._normalBias = 0;
  64632. this._blurBoxOffset = 1;
  64633. this._blurScale = 2;
  64634. this._blurKernel = 1;
  64635. this._useKernelBlur = false;
  64636. this._filter = ShadowGenerator.FILTER_NONE;
  64637. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64638. this._contactHardeningLightSizeUVRatio = 0.1;
  64639. this._darkness = 0;
  64640. this._transparencyShadow = false;
  64641. /**
  64642. * Controls the extent to which the shadows fade out at the edge of the frustum
  64643. * Used only by directionals and spots
  64644. */
  64645. this.frustumEdgeFalloff = 0;
  64646. /**
  64647. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64648. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64649. * It might on the other hand introduce peter panning.
  64650. */
  64651. this.forceBackFacesOnly = false;
  64652. this._lightDirection = BABYLON.Vector3.Zero();
  64653. this._viewMatrix = BABYLON.Matrix.Zero();
  64654. this._projectionMatrix = BABYLON.Matrix.Zero();
  64655. this._transformMatrix = BABYLON.Matrix.Zero();
  64656. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64657. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64658. this._currentFaceIndex = 0;
  64659. this._currentFaceIndexCache = 0;
  64660. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64661. this._mapSize = mapSize;
  64662. this._light = light;
  64663. this._scene = light.getScene();
  64664. light._shadowGenerator = this;
  64665. // Texture type fallback from float to int if not supported.
  64666. var caps = this._scene.getEngine().getCaps();
  64667. if (!useFullFloatFirst) {
  64668. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64669. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64670. }
  64671. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64672. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64673. }
  64674. else {
  64675. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64676. }
  64677. }
  64678. else {
  64679. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64680. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64681. }
  64682. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64683. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64684. }
  64685. else {
  64686. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64687. }
  64688. }
  64689. this._initializeGenerator();
  64690. this._applyFilterValues();
  64691. }
  64692. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64693. /**
  64694. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64695. */
  64696. get: function () {
  64697. return this._bias;
  64698. },
  64699. /**
  64700. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64701. */
  64702. set: function (bias) {
  64703. this._bias = bias;
  64704. },
  64705. enumerable: true,
  64706. configurable: true
  64707. });
  64708. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64709. /**
  64710. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64711. */
  64712. get: function () {
  64713. return this._normalBias;
  64714. },
  64715. /**
  64716. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64717. */
  64718. set: function (normalBias) {
  64719. this._normalBias = normalBias;
  64720. },
  64721. enumerable: true,
  64722. configurable: true
  64723. });
  64724. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64725. /**
  64726. * Gets the blur box offset: offset applied during the blur pass.
  64727. * Only usefull if useKernelBlur = false
  64728. */
  64729. get: function () {
  64730. return this._blurBoxOffset;
  64731. },
  64732. /**
  64733. * Sets the blur box offset: offset applied during the blur pass.
  64734. * Only usefull if useKernelBlur = false
  64735. */
  64736. set: function (value) {
  64737. if (this._blurBoxOffset === value) {
  64738. return;
  64739. }
  64740. this._blurBoxOffset = value;
  64741. this._disposeBlurPostProcesses();
  64742. },
  64743. enumerable: true,
  64744. configurable: true
  64745. });
  64746. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64747. /**
  64748. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64749. * 2 means half of the size.
  64750. */
  64751. get: function () {
  64752. return this._blurScale;
  64753. },
  64754. /**
  64755. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64756. * 2 means half of the size.
  64757. */
  64758. set: function (value) {
  64759. if (this._blurScale === value) {
  64760. return;
  64761. }
  64762. this._blurScale = value;
  64763. this._disposeBlurPostProcesses();
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64769. /**
  64770. * Gets the blur kernel: kernel size of the blur pass.
  64771. * Only usefull if useKernelBlur = true
  64772. */
  64773. get: function () {
  64774. return this._blurKernel;
  64775. },
  64776. /**
  64777. * Sets the blur kernel: kernel size of the blur pass.
  64778. * Only usefull if useKernelBlur = true
  64779. */
  64780. set: function (value) {
  64781. if (this._blurKernel === value) {
  64782. return;
  64783. }
  64784. this._blurKernel = value;
  64785. this._disposeBlurPostProcesses();
  64786. },
  64787. enumerable: true,
  64788. configurable: true
  64789. });
  64790. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64791. /**
  64792. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64793. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64794. */
  64795. get: function () {
  64796. return this._useKernelBlur;
  64797. },
  64798. /**
  64799. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64800. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64801. */
  64802. set: function (value) {
  64803. if (this._useKernelBlur === value) {
  64804. return;
  64805. }
  64806. this._useKernelBlur = value;
  64807. this._disposeBlurPostProcesses();
  64808. },
  64809. enumerable: true,
  64810. configurable: true
  64811. });
  64812. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64813. /**
  64814. * Gets the depth scale used in ESM mode.
  64815. */
  64816. get: function () {
  64817. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64818. },
  64819. /**
  64820. * Sets the depth scale used in ESM mode.
  64821. * This can override the scale stored on the light.
  64822. */
  64823. set: function (value) {
  64824. this._depthScale = value;
  64825. },
  64826. enumerable: true,
  64827. configurable: true
  64828. });
  64829. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64830. /**
  64831. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64832. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64833. */
  64834. get: function () {
  64835. return this._filter;
  64836. },
  64837. /**
  64838. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64839. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64840. */
  64841. set: function (value) {
  64842. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64843. if (this._light.needCube()) {
  64844. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64845. this.useExponentialShadowMap = true;
  64846. return;
  64847. }
  64848. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64849. this.useCloseExponentialShadowMap = true;
  64850. return;
  64851. }
  64852. // PCF on cubemap would also be expensive
  64853. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64854. this.usePoissonSampling = true;
  64855. return;
  64856. }
  64857. }
  64858. // Weblg1 fallback for PCF.
  64859. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64860. if (this._scene.getEngine().webGLVersion === 1) {
  64861. this.usePoissonSampling = true;
  64862. return;
  64863. }
  64864. }
  64865. if (this._filter === value) {
  64866. return;
  64867. }
  64868. this._filter = value;
  64869. this._disposeBlurPostProcesses();
  64870. this._applyFilterValues();
  64871. this._light._markMeshesAsLightDirty();
  64872. },
  64873. enumerable: true,
  64874. configurable: true
  64875. });
  64876. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64877. /**
  64878. * Gets if the current filter is set to Poisson Sampling.
  64879. */
  64880. get: function () {
  64881. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64882. },
  64883. /**
  64884. * Sets the current filter to Poisson Sampling.
  64885. */
  64886. set: function (value) {
  64887. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64888. return;
  64889. }
  64890. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64891. },
  64892. enumerable: true,
  64893. configurable: true
  64894. });
  64895. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64896. /**
  64897. * Gets if the current filter is set to VSM.
  64898. * DEPRECATED. Should use useExponentialShadowMap instead.
  64899. */
  64900. get: function () {
  64901. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64902. return this.useExponentialShadowMap;
  64903. },
  64904. /**
  64905. * Sets the current filter is to VSM.
  64906. * DEPRECATED. Should use useExponentialShadowMap instead.
  64907. */
  64908. set: function (value) {
  64909. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64910. this.useExponentialShadowMap = value;
  64911. },
  64912. enumerable: true,
  64913. configurable: true
  64914. });
  64915. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64916. /**
  64917. * Gets if the current filter is set to blurred VSM.
  64918. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64919. */
  64920. get: function () {
  64921. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64922. return this.useBlurExponentialShadowMap;
  64923. },
  64924. /**
  64925. * Sets the current filter is to blurred VSM.
  64926. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64927. */
  64928. set: function (value) {
  64929. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64930. this.useBlurExponentialShadowMap = value;
  64931. },
  64932. enumerable: true,
  64933. configurable: true
  64934. });
  64935. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64936. /**
  64937. * Gets if the current filter is set to ESM.
  64938. */
  64939. get: function () {
  64940. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64941. },
  64942. /**
  64943. * Sets the current filter is to ESM.
  64944. */
  64945. set: function (value) {
  64946. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64947. return;
  64948. }
  64949. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64955. /**
  64956. * Gets if the current filter is set to filtered ESM.
  64957. */
  64958. get: function () {
  64959. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64960. },
  64961. /**
  64962. * Gets if the current filter is set to filtered ESM.
  64963. */
  64964. set: function (value) {
  64965. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64966. return;
  64967. }
  64968. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64969. },
  64970. enumerable: true,
  64971. configurable: true
  64972. });
  64973. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64974. /**
  64975. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64976. * exponential to prevent steep falloff artifacts).
  64977. */
  64978. get: function () {
  64979. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64980. },
  64981. /**
  64982. * Sets the current filter to "close ESM" (using the inverse of the
  64983. * exponential to prevent steep falloff artifacts).
  64984. */
  64985. set: function (value) {
  64986. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64987. return;
  64988. }
  64989. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64990. },
  64991. enumerable: true,
  64992. configurable: true
  64993. });
  64994. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64995. /**
  64996. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64997. * exponential to prevent steep falloff artifacts).
  64998. */
  64999. get: function () {
  65000. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65001. },
  65002. /**
  65003. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65004. * exponential to prevent steep falloff artifacts).
  65005. */
  65006. set: function (value) {
  65007. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65008. return;
  65009. }
  65010. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65011. },
  65012. enumerable: true,
  65013. configurable: true
  65014. });
  65015. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65016. /**
  65017. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65018. */
  65019. get: function () {
  65020. return this.filter === ShadowGenerator.FILTER_PCF;
  65021. },
  65022. /**
  65023. * Sets the current filter to "PCF" (percentage closer filtering).
  65024. */
  65025. set: function (value) {
  65026. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65027. return;
  65028. }
  65029. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65030. },
  65031. enumerable: true,
  65032. configurable: true
  65033. });
  65034. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65035. /**
  65036. * Gets the PCF or PCSS Quality.
  65037. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65038. */
  65039. get: function () {
  65040. return this._filteringQuality;
  65041. },
  65042. /**
  65043. * Sets the PCF or PCSS Quality.
  65044. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65045. */
  65046. set: function (filteringQuality) {
  65047. this._filteringQuality = filteringQuality;
  65048. },
  65049. enumerable: true,
  65050. configurable: true
  65051. });
  65052. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65053. /**
  65054. * Gets if the current filter is set to "PCSS" (contact hardening).
  65055. */
  65056. get: function () {
  65057. return this.filter === ShadowGenerator.FILTER_PCSS;
  65058. },
  65059. /**
  65060. * Sets the current filter to "PCSS" (contact hardening).
  65061. */
  65062. set: function (value) {
  65063. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65064. return;
  65065. }
  65066. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65067. },
  65068. enumerable: true,
  65069. configurable: true
  65070. });
  65071. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65072. /**
  65073. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65074. * Using a ratio helps keeping shape stability independently of the map size.
  65075. *
  65076. * It does not account for the light projection as it was having too much
  65077. * instability during the light setup or during light position changes.
  65078. *
  65079. * Only valid if useContactHardeningShadow is true.
  65080. */
  65081. get: function () {
  65082. return this._contactHardeningLightSizeUVRatio;
  65083. },
  65084. /**
  65085. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65086. * Using a ratio helps keeping shape stability independently of the map size.
  65087. *
  65088. * It does not account for the light projection as it was having too much
  65089. * instability during the light setup or during light position changes.
  65090. *
  65091. * Only valid if useContactHardeningShadow is true.
  65092. */
  65093. set: function (contactHardeningLightSizeUVRatio) {
  65094. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65095. },
  65096. enumerable: true,
  65097. configurable: true
  65098. });
  65099. /**
  65100. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65101. * 0 means strongest and 1 would means no shadow.
  65102. * @returns the darkness.
  65103. */
  65104. ShadowGenerator.prototype.getDarkness = function () {
  65105. return this._darkness;
  65106. };
  65107. /**
  65108. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65109. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65110. * @returns the shadow generator allowing fluent coding.
  65111. */
  65112. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65113. if (darkness >= 1.0)
  65114. this._darkness = 1.0;
  65115. else if (darkness <= 0.0)
  65116. this._darkness = 0.0;
  65117. else
  65118. this._darkness = darkness;
  65119. return this;
  65120. };
  65121. /**
  65122. * Sets the ability to have transparent shadow (boolean).
  65123. * @param transparent True if transparent else False
  65124. * @returns the shadow generator allowing fluent coding
  65125. */
  65126. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65127. this._transparencyShadow = transparent;
  65128. return this;
  65129. };
  65130. /**
  65131. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65132. * @returns The render target texture if present otherwise, null
  65133. */
  65134. ShadowGenerator.prototype.getShadowMap = function () {
  65135. return this._shadowMap;
  65136. };
  65137. /**
  65138. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65139. * @returns The render target texture if the shadow map is present otherwise, null
  65140. */
  65141. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65142. if (this._shadowMap2) {
  65143. return this._shadowMap2;
  65144. }
  65145. return this._shadowMap;
  65146. };
  65147. /**
  65148. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65149. * @param mesh Mesh to add
  65150. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65151. * @returns the Shadow Generator itself
  65152. */
  65153. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65154. if (includeDescendants === void 0) { includeDescendants = true; }
  65155. if (!this._shadowMap) {
  65156. return this;
  65157. }
  65158. if (!this._shadowMap.renderList) {
  65159. this._shadowMap.renderList = [];
  65160. }
  65161. this._shadowMap.renderList.push(mesh);
  65162. if (includeDescendants) {
  65163. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65164. }
  65165. return this;
  65166. var _a;
  65167. };
  65168. /**
  65169. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65170. * @param mesh Mesh to remove
  65171. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65172. * @returns the Shadow Generator itself
  65173. */
  65174. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65175. if (includeDescendants === void 0) { includeDescendants = true; }
  65176. if (!this._shadowMap || !this._shadowMap.renderList) {
  65177. return this;
  65178. }
  65179. var index = this._shadowMap.renderList.indexOf(mesh);
  65180. if (index !== -1) {
  65181. this._shadowMap.renderList.splice(index, 1);
  65182. }
  65183. if (includeDescendants) {
  65184. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65185. var child = _a[_i];
  65186. this.removeShadowCaster(child);
  65187. }
  65188. }
  65189. return this;
  65190. };
  65191. /**
  65192. * Returns the associated light object.
  65193. * @returns the light generating the shadow
  65194. */
  65195. ShadowGenerator.prototype.getLight = function () {
  65196. return this._light;
  65197. };
  65198. ShadowGenerator.prototype._initializeGenerator = function () {
  65199. this._light._markMeshesAsLightDirty();
  65200. this._initializeShadowMap();
  65201. };
  65202. ShadowGenerator.prototype._initializeShadowMap = function () {
  65203. var _this = this;
  65204. // Render target
  65205. var engine = this._scene.getEngine();
  65206. if (engine.webGLVersion > 1) {
  65207. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65208. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65209. }
  65210. else {
  65211. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65212. }
  65213. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65214. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65215. this._shadowMap.anisotropicFilteringLevel = 1;
  65216. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65217. this._shadowMap.renderParticles = false;
  65218. this._shadowMap.ignoreCameraViewport = true;
  65219. // Record Face Index before render.
  65220. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65221. _this._currentFaceIndex = faceIndex;
  65222. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65223. engine.setColorWrite(false);
  65224. }
  65225. });
  65226. // Custom render function.
  65227. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65228. // Blur if required afer render.
  65229. this._shadowMap.onAfterUnbindObservable.add(function () {
  65230. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65231. engine.setColorWrite(true);
  65232. }
  65233. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65234. return;
  65235. }
  65236. var shadowMap = _this.getShadowMapForRendering();
  65237. if (shadowMap) {
  65238. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65239. }
  65240. });
  65241. // Clear according to the chosen filter.
  65242. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65243. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65244. this._shadowMap.onClearObservable.add(function (engine) {
  65245. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65246. engine.clear(clearOne, false, true, false);
  65247. }
  65248. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65249. engine.clear(clearZero, true, true, false);
  65250. }
  65251. else {
  65252. engine.clear(clearOne, true, true, false);
  65253. }
  65254. });
  65255. };
  65256. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65257. var _this = this;
  65258. var engine = this._scene.getEngine();
  65259. var targetSize = this._mapSize / this.blurScale;
  65260. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65261. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65262. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65263. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65264. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65265. }
  65266. if (this.useKernelBlur) {
  65267. 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);
  65268. this._kernelBlurXPostprocess.width = targetSize;
  65269. this._kernelBlurXPostprocess.height = targetSize;
  65270. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65271. effect.setTexture("textureSampler", _this._shadowMap);
  65272. });
  65273. 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);
  65274. this._kernelBlurXPostprocess.autoClear = false;
  65275. this._kernelBlurYPostprocess.autoClear = false;
  65276. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65277. this._kernelBlurXPostprocess.packedFloat = true;
  65278. this._kernelBlurYPostprocess.packedFloat = true;
  65279. }
  65280. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65281. }
  65282. else {
  65283. 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);
  65284. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65285. effect.setFloat2("screenSize", targetSize, targetSize);
  65286. effect.setTexture("textureSampler", _this._shadowMap);
  65287. });
  65288. this._boxBlurPostprocess.autoClear = false;
  65289. this._blurPostProcesses = [this._boxBlurPostprocess];
  65290. }
  65291. };
  65292. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65293. var index;
  65294. var engine = this._scene.getEngine();
  65295. if (depthOnlySubMeshes.length) {
  65296. engine.setColorWrite(false);
  65297. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65298. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65299. }
  65300. engine.setColorWrite(true);
  65301. }
  65302. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65303. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65304. }
  65305. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65306. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65307. }
  65308. if (this._transparencyShadow) {
  65309. for (index = 0; index < transparentSubMeshes.length; index++) {
  65310. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65311. }
  65312. }
  65313. };
  65314. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65315. var _this = this;
  65316. var mesh = subMesh.getRenderingMesh();
  65317. var scene = this._scene;
  65318. var engine = scene.getEngine();
  65319. var material = subMesh.getMaterial();
  65320. if (!material) {
  65321. return;
  65322. }
  65323. // Culling
  65324. engine.setState(material.backFaceCulling);
  65325. // Managing instances
  65326. var batch = mesh._getInstancesRenderList(subMesh._id);
  65327. if (batch.mustReturn) {
  65328. return;
  65329. }
  65330. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65331. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65332. engine.enableEffect(this._effect);
  65333. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65334. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65335. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65336. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65337. this._effect.setVector3("lightData", this._cachedDirection);
  65338. }
  65339. else {
  65340. this._effect.setVector3("lightData", this._cachedPosition);
  65341. }
  65342. if (scene.activeCamera) {
  65343. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65344. }
  65345. // Alpha test
  65346. if (material && material.needAlphaTesting()) {
  65347. var alphaTexture = material.getAlphaTestTexture();
  65348. if (alphaTexture) {
  65349. this._effect.setTexture("diffuseSampler", alphaTexture);
  65350. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65351. }
  65352. }
  65353. // Bones
  65354. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65355. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65356. }
  65357. // Morph targets
  65358. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65359. if (this.forceBackFacesOnly) {
  65360. engine.setState(true, 0, false, true);
  65361. }
  65362. // Draw
  65363. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65364. if (this.forceBackFacesOnly) {
  65365. engine.setState(true, 0, false, false);
  65366. }
  65367. }
  65368. else {
  65369. // Need to reset refresh rate of the shadowMap
  65370. if (this._shadowMap) {
  65371. this._shadowMap.resetRefreshCounter();
  65372. }
  65373. }
  65374. };
  65375. ShadowGenerator.prototype._applyFilterValues = function () {
  65376. if (!this._shadowMap) {
  65377. return;
  65378. }
  65379. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65380. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65381. }
  65382. else {
  65383. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65384. }
  65385. };
  65386. /**
  65387. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65388. * @param onCompiled Callback triggered at the and of the effects compilation
  65389. * @param options Sets of optional options forcing the compilation with different modes
  65390. */
  65391. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65392. var _this = this;
  65393. var localOptions = __assign({ useInstances: false }, options);
  65394. var shadowMap = this.getShadowMap();
  65395. if (!shadowMap) {
  65396. if (onCompiled) {
  65397. onCompiled(this);
  65398. }
  65399. return;
  65400. }
  65401. var renderList = shadowMap.renderList;
  65402. if (!renderList) {
  65403. if (onCompiled) {
  65404. onCompiled(this);
  65405. }
  65406. return;
  65407. }
  65408. var subMeshes = new Array();
  65409. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65410. var mesh = renderList_1[_i];
  65411. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65412. }
  65413. if (subMeshes.length === 0) {
  65414. if (onCompiled) {
  65415. onCompiled(this);
  65416. }
  65417. return;
  65418. }
  65419. var currentIndex = 0;
  65420. var checkReady = function () {
  65421. if (!_this._scene || !_this._scene.getEngine()) {
  65422. return;
  65423. }
  65424. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65425. currentIndex++;
  65426. if (currentIndex >= subMeshes.length) {
  65427. if (onCompiled) {
  65428. onCompiled(_this);
  65429. }
  65430. return;
  65431. }
  65432. }
  65433. setTimeout(checkReady, 16);
  65434. };
  65435. checkReady();
  65436. };
  65437. /**
  65438. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65439. * @param options Sets of optional options forcing the compilation with different modes
  65440. * @returns A promise that resolves when the compilation completes
  65441. */
  65442. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65443. var _this = this;
  65444. return new Promise(function (resolve) {
  65445. _this.forceCompilation(function () {
  65446. resolve();
  65447. }, options);
  65448. });
  65449. };
  65450. /**
  65451. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65452. * @param subMesh The submesh we want to render in the shadow map
  65453. * @param useInstances Defines wether will draw in the map using instances
  65454. * @returns true if ready otherwise, false
  65455. */
  65456. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65457. var defines = [];
  65458. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65459. defines.push("#define FLOAT");
  65460. }
  65461. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65462. defines.push("#define ESM");
  65463. }
  65464. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65465. defines.push("#define DEPTHTEXTURE");
  65466. }
  65467. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65468. var mesh = subMesh.getMesh();
  65469. var material = subMesh.getMaterial();
  65470. // Normal bias.
  65471. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65472. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65473. defines.push("#define NORMAL");
  65474. if (mesh.nonUniformScaling) {
  65475. defines.push("#define NONUNIFORMSCALING");
  65476. }
  65477. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65478. defines.push("#define DIRECTIONINLIGHTDATA");
  65479. }
  65480. }
  65481. // Alpha test
  65482. if (material && material.needAlphaTesting()) {
  65483. var alphaTexture = material.getAlphaTestTexture();
  65484. if (alphaTexture) {
  65485. defines.push("#define ALPHATEST");
  65486. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65487. attribs.push(BABYLON.VertexBuffer.UVKind);
  65488. defines.push("#define UV1");
  65489. }
  65490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65491. if (alphaTexture.coordinatesIndex === 1) {
  65492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65493. defines.push("#define UV2");
  65494. }
  65495. }
  65496. }
  65497. }
  65498. // Bones
  65499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65502. if (mesh.numBoneInfluencers > 4) {
  65503. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65504. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65505. }
  65506. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65507. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65508. }
  65509. else {
  65510. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65511. }
  65512. // Morph targets
  65513. var manager = mesh.morphTargetManager;
  65514. var morphInfluencers = 0;
  65515. if (manager) {
  65516. if (manager.numInfluencers > 0) {
  65517. defines.push("#define MORPHTARGETS");
  65518. morphInfluencers = manager.numInfluencers;
  65519. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65520. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65521. }
  65522. }
  65523. // Instances
  65524. if (useInstances) {
  65525. defines.push("#define INSTANCES");
  65526. attribs.push("world0");
  65527. attribs.push("world1");
  65528. attribs.push("world2");
  65529. attribs.push("world3");
  65530. }
  65531. // Get correct effect
  65532. var join = defines.join("\n");
  65533. if (this._cachedDefines !== join) {
  65534. this._cachedDefines = join;
  65535. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65536. }
  65537. if (!this._effect.isReady()) {
  65538. return false;
  65539. }
  65540. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65541. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65542. this._initializeBlurRTTAndPostProcesses();
  65543. }
  65544. }
  65545. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65546. return false;
  65547. }
  65548. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65549. return false;
  65550. }
  65551. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65552. return false;
  65553. }
  65554. return true;
  65555. };
  65556. /**
  65557. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65558. * @param defines Defines of the material we want to update
  65559. * @param lightIndex Index of the light in the enabled light list of the material
  65560. */
  65561. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65562. var scene = this._scene;
  65563. var light = this._light;
  65564. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65565. return;
  65566. }
  65567. defines["SHADOW" + lightIndex] = true;
  65568. if (this.useContactHardeningShadow) {
  65569. defines["SHADOWPCSS" + lightIndex] = true;
  65570. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65571. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65572. }
  65573. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65574. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65575. }
  65576. // else default to high.
  65577. }
  65578. if (this.usePercentageCloserFiltering) {
  65579. defines["SHADOWPCF" + lightIndex] = true;
  65580. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65581. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65582. }
  65583. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65584. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65585. }
  65586. // else default to high.
  65587. }
  65588. else if (this.usePoissonSampling) {
  65589. defines["SHADOWPOISSON" + lightIndex] = true;
  65590. }
  65591. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65592. defines["SHADOWESM" + lightIndex] = true;
  65593. }
  65594. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65595. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65596. }
  65597. if (light.needCube()) {
  65598. defines["SHADOWCUBE" + lightIndex] = true;
  65599. }
  65600. };
  65601. /**
  65602. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65603. * defined in the generator but impacting the effect).
  65604. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65605. * @param effect The effect we are binfing the information for
  65606. */
  65607. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65608. var light = this._light;
  65609. var scene = this._scene;
  65610. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65611. return;
  65612. }
  65613. var camera = scene.activeCamera;
  65614. if (!camera) {
  65615. return;
  65616. }
  65617. var shadowMap = this.getShadowMap();
  65618. if (!shadowMap) {
  65619. return;
  65620. }
  65621. if (!light.needCube()) {
  65622. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65623. }
  65624. // Only PCF uses depth stencil texture.
  65625. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65626. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65627. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65628. }
  65629. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65630. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65631. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65632. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65633. }
  65634. else {
  65635. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65636. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65637. }
  65638. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65639. };
  65640. /**
  65641. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65642. * (eq to shadow prjection matrix * light transform matrix)
  65643. * @returns The transform matrix used to create the shadow map
  65644. */
  65645. ShadowGenerator.prototype.getTransformMatrix = function () {
  65646. var scene = this._scene;
  65647. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65648. return this._transformMatrix;
  65649. }
  65650. this._currentRenderID = scene.getRenderId();
  65651. this._currentFaceIndexCache = this._currentFaceIndex;
  65652. var lightPosition = this._light.position;
  65653. if (this._light.computeTransformedInformation()) {
  65654. lightPosition = this._light.transformedPosition;
  65655. }
  65656. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65657. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65658. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65659. }
  65660. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65661. this._cachedPosition.copyFrom(lightPosition);
  65662. this._cachedDirection.copyFrom(this._lightDirection);
  65663. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65664. var shadowMap = this.getShadowMap();
  65665. if (shadowMap) {
  65666. var renderList = shadowMap.renderList;
  65667. if (renderList) {
  65668. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65669. }
  65670. }
  65671. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65672. }
  65673. return this._transformMatrix;
  65674. };
  65675. /**
  65676. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65677. * Cube and 2D textures for instance.
  65678. */
  65679. ShadowGenerator.prototype.recreateShadowMap = function () {
  65680. var shadowMap = this._shadowMap;
  65681. if (!shadowMap) {
  65682. return;
  65683. }
  65684. // Track render list.
  65685. var renderList = shadowMap.renderList;
  65686. // Clean up existing data.
  65687. this._disposeRTTandPostProcesses();
  65688. // Reinitializes.
  65689. this._initializeGenerator();
  65690. // Reaffect the filter to ensure a correct fallback if necessary.
  65691. this.filter = this.filter;
  65692. // Reaffect the filter.
  65693. this._applyFilterValues();
  65694. // Reaffect Render List.
  65695. this._shadowMap.renderList = renderList;
  65696. };
  65697. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65698. if (this._shadowMap2) {
  65699. this._shadowMap2.dispose();
  65700. this._shadowMap2 = null;
  65701. }
  65702. if (this._boxBlurPostprocess) {
  65703. this._boxBlurPostprocess.dispose();
  65704. this._boxBlurPostprocess = null;
  65705. }
  65706. if (this._kernelBlurXPostprocess) {
  65707. this._kernelBlurXPostprocess.dispose();
  65708. this._kernelBlurXPostprocess = null;
  65709. }
  65710. if (this._kernelBlurYPostprocess) {
  65711. this._kernelBlurYPostprocess.dispose();
  65712. this._kernelBlurYPostprocess = null;
  65713. }
  65714. this._blurPostProcesses = [];
  65715. };
  65716. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65717. if (this._shadowMap) {
  65718. this._shadowMap.dispose();
  65719. this._shadowMap = null;
  65720. }
  65721. this._disposeBlurPostProcesses();
  65722. };
  65723. /**
  65724. * Disposes the ShadowGenerator.
  65725. * Returns nothing.
  65726. */
  65727. ShadowGenerator.prototype.dispose = function () {
  65728. this._disposeRTTandPostProcesses();
  65729. if (this._light) {
  65730. this._light._shadowGenerator = null;
  65731. this._light._markMeshesAsLightDirty();
  65732. }
  65733. };
  65734. /**
  65735. * Serializes the shadow generator setup to a json object.
  65736. * @returns The serialized JSON object
  65737. */
  65738. ShadowGenerator.prototype.serialize = function () {
  65739. var serializationObject = {};
  65740. var shadowMap = this.getShadowMap();
  65741. if (!shadowMap) {
  65742. return serializationObject;
  65743. }
  65744. serializationObject.lightId = this._light.id;
  65745. serializationObject.mapSize = shadowMap.getRenderSize();
  65746. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65747. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65748. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65749. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65750. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65751. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65752. serializationObject.depthScale = this.depthScale;
  65753. serializationObject.darkness = this.getDarkness();
  65754. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65755. serializationObject.blurKernel = this.blurKernel;
  65756. serializationObject.blurScale = this.blurScale;
  65757. serializationObject.useKernelBlur = this.useKernelBlur;
  65758. serializationObject.transparencyShadow = this._transparencyShadow;
  65759. serializationObject.bias = this.bias;
  65760. serializationObject.normalBias = this.normalBias;
  65761. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65762. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65763. serializationObject.filteringQuality = this.filteringQuality;
  65764. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65765. serializationObject.renderList = [];
  65766. if (shadowMap.renderList) {
  65767. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65768. var mesh = shadowMap.renderList[meshIndex];
  65769. serializationObject.renderList.push(mesh.id);
  65770. }
  65771. }
  65772. return serializationObject;
  65773. };
  65774. /**
  65775. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65776. * @param parsedShadowGenerator The JSON object to parse
  65777. * @param scene The scene to create the shadow map for
  65778. * @returns The parsed shadow generator
  65779. */
  65780. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65781. //casting to point light, as light is missing the position attr and typescript complains.
  65782. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65783. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65784. var shadowMap = shadowGenerator.getShadowMap();
  65785. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65786. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65787. meshes.forEach(function (mesh) {
  65788. if (!shadowMap) {
  65789. return;
  65790. }
  65791. if (!shadowMap.renderList) {
  65792. shadowMap.renderList = [];
  65793. }
  65794. shadowMap.renderList.push(mesh);
  65795. });
  65796. }
  65797. if (parsedShadowGenerator.usePoissonSampling) {
  65798. shadowGenerator.usePoissonSampling = true;
  65799. }
  65800. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65801. shadowGenerator.useExponentialShadowMap = true;
  65802. }
  65803. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65804. shadowGenerator.useBlurExponentialShadowMap = true;
  65805. }
  65806. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65807. shadowGenerator.useCloseExponentialShadowMap = true;
  65808. }
  65809. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65810. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65811. }
  65812. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65813. shadowGenerator.usePercentageCloserFiltering = true;
  65814. }
  65815. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65816. shadowGenerator.useContactHardeningShadow = true;
  65817. }
  65818. if (parsedShadowGenerator.filteringQuality) {
  65819. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65820. }
  65821. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65822. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65823. }
  65824. // Backward compat
  65825. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65826. shadowGenerator.useExponentialShadowMap = true;
  65827. }
  65828. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65829. shadowGenerator.useBlurExponentialShadowMap = true;
  65830. }
  65831. if (parsedShadowGenerator.depthScale) {
  65832. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65833. }
  65834. if (parsedShadowGenerator.blurScale) {
  65835. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65836. }
  65837. if (parsedShadowGenerator.blurBoxOffset) {
  65838. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65839. }
  65840. if (parsedShadowGenerator.useKernelBlur) {
  65841. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65842. }
  65843. if (parsedShadowGenerator.blurKernel) {
  65844. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65845. }
  65846. if (parsedShadowGenerator.bias !== undefined) {
  65847. shadowGenerator.bias = parsedShadowGenerator.bias;
  65848. }
  65849. if (parsedShadowGenerator.normalBias !== undefined) {
  65850. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65851. }
  65852. if (parsedShadowGenerator.darkness) {
  65853. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65854. }
  65855. if (parsedShadowGenerator.transparencyShadow) {
  65856. shadowGenerator.setTransparencyShadow(true);
  65857. }
  65858. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65859. return shadowGenerator;
  65860. };
  65861. /**
  65862. * Shadow generator mode None: no filtering applied.
  65863. */
  65864. ShadowGenerator.FILTER_NONE = 0;
  65865. /**
  65866. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65867. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65868. */
  65869. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65870. /**
  65871. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65872. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65873. */
  65874. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65875. /**
  65876. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65877. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65878. */
  65879. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65880. /**
  65881. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65882. * edge artifacts on steep falloff.
  65883. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65884. */
  65885. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65886. /**
  65887. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65888. * edge artifacts on steep falloff.
  65889. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65890. */
  65891. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65892. /**
  65893. * Shadow generator mode PCF: Percentage Closer Filtering
  65894. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65895. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65896. */
  65897. ShadowGenerator.FILTER_PCF = 6;
  65898. /**
  65899. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65900. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65901. * Contact Hardening
  65902. */
  65903. ShadowGenerator.FILTER_PCSS = 7;
  65904. /**
  65905. * Reserved for PCF and PCSS
  65906. * Highest Quality.
  65907. *
  65908. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65909. *
  65910. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65911. */
  65912. ShadowGenerator.QUALITY_HIGH = 0;
  65913. /**
  65914. * Reserved for PCF and PCSS
  65915. * Good tradeoff for quality/perf cross devices
  65916. *
  65917. * Execute PCF on a 3*3 kernel.
  65918. *
  65919. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65920. */
  65921. ShadowGenerator.QUALITY_MEDIUM = 1;
  65922. /**
  65923. * Reserved for PCF and PCSS
  65924. * The lowest quality but the fastest.
  65925. *
  65926. * Execute PCF on a 1*1 kernel.
  65927. *
  65928. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65929. */
  65930. ShadowGenerator.QUALITY_LOW = 2;
  65931. return ShadowGenerator;
  65932. }());
  65933. BABYLON.ShadowGenerator = ShadowGenerator;
  65934. })(BABYLON || (BABYLON = {}));
  65935. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65936. var BABYLON;
  65937. (function (BABYLON) {
  65938. var DefaultLoadingScreen = /** @class */ (function () {
  65939. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65940. if (_loadingText === void 0) { _loadingText = ""; }
  65941. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65942. var _this = this;
  65943. this._renderingCanvas = _renderingCanvas;
  65944. this._loadingText = _loadingText;
  65945. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65946. // Resize
  65947. this._resizeLoadingUI = function () {
  65948. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65949. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65950. if (!_this._loadingDiv) {
  65951. return;
  65952. }
  65953. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65954. _this._loadingDiv.style.left = canvasRect.left + "px";
  65955. _this._loadingDiv.style.top = canvasRect.top + "px";
  65956. _this._loadingDiv.style.width = canvasRect.width + "px";
  65957. _this._loadingDiv.style.height = canvasRect.height + "px";
  65958. };
  65959. }
  65960. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65961. if (this._loadingDiv) {
  65962. // Do not add a loading screen if there is already one
  65963. return;
  65964. }
  65965. this._loadingDiv = document.createElement("div");
  65966. this._loadingDiv.id = "babylonjsLoadingDiv";
  65967. this._loadingDiv.style.opacity = "0";
  65968. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65969. this._loadingDiv.style.pointerEvents = "none";
  65970. // Loading text
  65971. this._loadingTextDiv = document.createElement("div");
  65972. this._loadingTextDiv.style.position = "absolute";
  65973. this._loadingTextDiv.style.left = "0";
  65974. this._loadingTextDiv.style.top = "50%";
  65975. this._loadingTextDiv.style.marginTop = "80px";
  65976. this._loadingTextDiv.style.width = "100%";
  65977. this._loadingTextDiv.style.height = "20px";
  65978. this._loadingTextDiv.style.fontFamily = "Arial";
  65979. this._loadingTextDiv.style.fontSize = "14px";
  65980. this._loadingTextDiv.style.color = "white";
  65981. this._loadingTextDiv.style.textAlign = "center";
  65982. this._loadingTextDiv.innerHTML = "Loading";
  65983. this._loadingDiv.appendChild(this._loadingTextDiv);
  65984. //set the predefined text
  65985. this._loadingTextDiv.innerHTML = this._loadingText;
  65986. // Generating keyframes
  65987. var style = document.createElement('style');
  65988. style.type = 'text/css';
  65989. 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 }";
  65990. style.innerHTML = keyFrames;
  65991. document.getElementsByTagName('head')[0].appendChild(style);
  65992. // Loading img
  65993. var imgBack = new Image();
  65994. 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";
  65995. imgBack.style.position = "absolute";
  65996. imgBack.style.left = "50%";
  65997. imgBack.style.top = "50%";
  65998. imgBack.style.marginLeft = "-60px";
  65999. imgBack.style.marginTop = "-60px";
  66000. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66001. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66002. imgBack.style.transformOrigin = "50% 50%";
  66003. imgBack.style.webkitTransformOrigin = "50% 50%";
  66004. this._loadingDiv.appendChild(imgBack);
  66005. this._resizeLoadingUI();
  66006. window.addEventListener("resize", this._resizeLoadingUI);
  66007. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66008. document.body.appendChild(this._loadingDiv);
  66009. this._loadingDiv.style.opacity = "1";
  66010. };
  66011. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66012. var _this = this;
  66013. if (!this._loadingDiv) {
  66014. return;
  66015. }
  66016. var onTransitionEnd = function () {
  66017. if (!_this._loadingDiv) {
  66018. return;
  66019. }
  66020. document.body.removeChild(_this._loadingDiv);
  66021. window.removeEventListener("resize", _this._resizeLoadingUI);
  66022. _this._loadingDiv = null;
  66023. };
  66024. this._loadingDiv.style.opacity = "0";
  66025. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66026. };
  66027. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66028. set: function (text) {
  66029. this._loadingText = text;
  66030. if (this._loadingTextDiv) {
  66031. this._loadingTextDiv.innerHTML = this._loadingText;
  66032. }
  66033. },
  66034. enumerable: true,
  66035. configurable: true
  66036. });
  66037. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66038. get: function () {
  66039. return this._loadingDivBackgroundColor;
  66040. },
  66041. set: function (color) {
  66042. this._loadingDivBackgroundColor = color;
  66043. if (!this._loadingDiv) {
  66044. return;
  66045. }
  66046. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. return DefaultLoadingScreen;
  66052. }());
  66053. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66054. })(BABYLON || (BABYLON = {}));
  66055. //# sourceMappingURL=babylon.loadingScreen.js.map
  66056. var BABYLON;
  66057. (function (BABYLON) {
  66058. var SceneLoaderProgressEvent = /** @class */ (function () {
  66059. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66060. this.lengthComputable = lengthComputable;
  66061. this.loaded = loaded;
  66062. this.total = total;
  66063. }
  66064. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66065. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66066. };
  66067. return SceneLoaderProgressEvent;
  66068. }());
  66069. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66070. var SceneLoader = /** @class */ (function () {
  66071. function SceneLoader() {
  66072. }
  66073. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66074. get: function () {
  66075. return 0;
  66076. },
  66077. enumerable: true,
  66078. configurable: true
  66079. });
  66080. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66081. get: function () {
  66082. return 1;
  66083. },
  66084. enumerable: true,
  66085. configurable: true
  66086. });
  66087. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66088. get: function () {
  66089. return 2;
  66090. },
  66091. enumerable: true,
  66092. configurable: true
  66093. });
  66094. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66095. get: function () {
  66096. return 3;
  66097. },
  66098. enumerable: true,
  66099. configurable: true
  66100. });
  66101. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66102. get: function () {
  66103. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66104. },
  66105. set: function (value) {
  66106. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66107. },
  66108. enumerable: true,
  66109. configurable: true
  66110. });
  66111. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66112. get: function () {
  66113. return SceneLoader._ShowLoadingScreen;
  66114. },
  66115. set: function (value) {
  66116. SceneLoader._ShowLoadingScreen = value;
  66117. },
  66118. enumerable: true,
  66119. configurable: true
  66120. });
  66121. Object.defineProperty(SceneLoader, "loggingLevel", {
  66122. get: function () {
  66123. return SceneLoader._loggingLevel;
  66124. },
  66125. set: function (value) {
  66126. SceneLoader._loggingLevel = value;
  66127. },
  66128. enumerable: true,
  66129. configurable: true
  66130. });
  66131. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66132. get: function () {
  66133. return SceneLoader._CleanBoneMatrixWeights;
  66134. },
  66135. set: function (value) {
  66136. SceneLoader._CleanBoneMatrixWeights = value;
  66137. },
  66138. enumerable: true,
  66139. configurable: true
  66140. });
  66141. SceneLoader._getDefaultPlugin = function () {
  66142. return SceneLoader._registeredPlugins[".babylon"];
  66143. };
  66144. SceneLoader._getPluginForExtension = function (extension) {
  66145. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66146. if (registeredPlugin) {
  66147. return registeredPlugin;
  66148. }
  66149. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66150. return SceneLoader._getDefaultPlugin();
  66151. };
  66152. SceneLoader._getPluginForDirectLoad = function (data) {
  66153. for (var extension in SceneLoader._registeredPlugins) {
  66154. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66155. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66156. return SceneLoader._registeredPlugins[extension];
  66157. }
  66158. }
  66159. return SceneLoader._getDefaultPlugin();
  66160. };
  66161. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66162. if (sceneFilename.name) {
  66163. sceneFilename = sceneFilename.name;
  66164. }
  66165. var queryStringPosition = sceneFilename.indexOf("?");
  66166. if (queryStringPosition !== -1) {
  66167. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66168. }
  66169. var dotPosition = sceneFilename.lastIndexOf(".");
  66170. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66171. return SceneLoader._getPluginForExtension(extension);
  66172. };
  66173. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66174. SceneLoader._getDirectLoad = function (sceneFilename) {
  66175. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66176. return sceneFilename.substr(5);
  66177. }
  66178. return null;
  66179. };
  66180. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66181. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66182. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66183. var plugin;
  66184. if (registeredPlugin.plugin.createPlugin) {
  66185. plugin = registeredPlugin.plugin.createPlugin();
  66186. }
  66187. else {
  66188. plugin = registeredPlugin.plugin;
  66189. }
  66190. var useArrayBuffer = registeredPlugin.isBinary;
  66191. var database;
  66192. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66193. var dataCallback = function (data, responseURL) {
  66194. if (scene.isDisposed) {
  66195. onError("Scene has been disposed");
  66196. return;
  66197. }
  66198. scene.database = database;
  66199. onSuccess(plugin, data, responseURL);
  66200. };
  66201. var request = null;
  66202. var pluginDisposed = false;
  66203. var onDisposeObservable = plugin.onDisposeObservable;
  66204. if (onDisposeObservable) {
  66205. onDisposeObservable.add(function () {
  66206. pluginDisposed = true;
  66207. if (request) {
  66208. request.abort();
  66209. request = null;
  66210. }
  66211. onDispose();
  66212. });
  66213. }
  66214. var manifestChecked = function () {
  66215. if (pluginDisposed) {
  66216. return;
  66217. }
  66218. var url = rootUrl + sceneFilename;
  66219. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66220. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66221. } : undefined, database, useArrayBuffer, function (request, exception) {
  66222. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66223. });
  66224. };
  66225. if (directLoad) {
  66226. dataCallback(directLoad);
  66227. return plugin;
  66228. }
  66229. if (rootUrl.indexOf("file:") === -1) {
  66230. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  66231. if (canUseOfflineSupport) {
  66232. // Also check for exceptions
  66233. var exceptionFound = false;
  66234. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66235. var regex = _a[_i];
  66236. if (regex.test(rootUrl + sceneFilename)) {
  66237. exceptionFound = true;
  66238. break;
  66239. }
  66240. }
  66241. canUseOfflineSupport = !exceptionFound;
  66242. }
  66243. if (canUseOfflineSupport) {
  66244. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66245. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  66246. }
  66247. else {
  66248. manifestChecked();
  66249. }
  66250. }
  66251. // Loading file from disk via input file or drag'n'drop
  66252. else {
  66253. var fileOrString = sceneFilename;
  66254. if (fileOrString.name) { // File
  66255. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66256. }
  66257. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66258. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66259. }
  66260. else {
  66261. onError("Unable to find file named " + sceneFilename);
  66262. }
  66263. }
  66264. return plugin;
  66265. };
  66266. // Public functions
  66267. SceneLoader.GetPluginForExtension = function (extension) {
  66268. return SceneLoader._getPluginForExtension(extension).plugin;
  66269. };
  66270. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66271. return !!SceneLoader._registeredPlugins[extension];
  66272. };
  66273. SceneLoader.RegisterPlugin = function (plugin) {
  66274. if (typeof plugin.extensions === "string") {
  66275. var extension = plugin.extensions;
  66276. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66277. plugin: plugin,
  66278. isBinary: false
  66279. };
  66280. }
  66281. else {
  66282. var extensions = plugin.extensions;
  66283. Object.keys(extensions).forEach(function (extension) {
  66284. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66285. plugin: plugin,
  66286. isBinary: extensions[extension].isBinary
  66287. };
  66288. });
  66289. }
  66290. };
  66291. /**
  66292. * Import meshes into a scene
  66293. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66294. * @param rootUrl a string that defines the root url for scene and resources
  66295. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66296. * @param scene the instance of BABYLON.Scene to append to
  66297. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66298. * @param onProgress a callback with a progress event for each file being loaded
  66299. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66300. * @param pluginExtension the extension used to determine the plugin
  66301. * @returns The loaded plugin
  66302. */
  66303. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66304. if (onSuccess === void 0) { onSuccess = null; }
  66305. if (onProgress === void 0) { onProgress = null; }
  66306. if (onError === void 0) { onError = null; }
  66307. if (pluginExtension === void 0) { pluginExtension = null; }
  66308. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66309. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66310. return null;
  66311. }
  66312. var loadingToken = {};
  66313. scene._addPendingData(loadingToken);
  66314. var disposeHandler = function () {
  66315. scene._removePendingData(loadingToken);
  66316. };
  66317. var errorHandler = function (message, exception) {
  66318. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66319. if (onError) {
  66320. onError(scene, errorMessage, exception);
  66321. }
  66322. else {
  66323. BABYLON.Tools.Error(errorMessage);
  66324. // should the exception be thrown?
  66325. }
  66326. disposeHandler();
  66327. };
  66328. var progressHandler = onProgress ? function (event) {
  66329. try {
  66330. onProgress(event);
  66331. }
  66332. catch (e) {
  66333. errorHandler("Error in onProgress callback", e);
  66334. }
  66335. } : undefined;
  66336. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66337. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66338. if (onSuccess) {
  66339. try {
  66340. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66341. }
  66342. catch (e) {
  66343. errorHandler("Error in onSuccess callback", e);
  66344. }
  66345. }
  66346. scene._removePendingData(loadingToken);
  66347. };
  66348. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66349. if (plugin.rewriteRootURL) {
  66350. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66351. }
  66352. if (sceneFilename === "") {
  66353. if (sceneFilename === "") {
  66354. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66355. }
  66356. }
  66357. if (plugin.importMesh) {
  66358. var syncedPlugin = plugin;
  66359. var meshes = new Array();
  66360. var particleSystems = new Array();
  66361. var skeletons = new Array();
  66362. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66363. return;
  66364. }
  66365. scene.loadingPluginName = plugin.name;
  66366. successHandler(meshes, particleSystems, skeletons, []);
  66367. }
  66368. else {
  66369. var asyncedPlugin = plugin;
  66370. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66371. scene.loadingPluginName = plugin.name;
  66372. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66373. }).catch(function (error) {
  66374. errorHandler(error.message, error);
  66375. });
  66376. }
  66377. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66378. };
  66379. /**
  66380. * Import meshes into a scene
  66381. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66382. * @param rootUrl a string that defines the root url for scene and resources
  66383. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66384. * @param scene the instance of BABYLON.Scene to append to
  66385. * @param onProgress a callback with a progress event for each file being loaded
  66386. * @param pluginExtension the extension used to determine the plugin
  66387. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66388. */
  66389. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66390. if (onProgress === void 0) { onProgress = null; }
  66391. if (pluginExtension === void 0) { pluginExtension = null; }
  66392. return new Promise(function (resolve, reject) {
  66393. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66394. resolve({
  66395. meshes: meshes,
  66396. particleSystems: particleSystems,
  66397. skeletons: skeletons,
  66398. animationGroups: animationGroups
  66399. });
  66400. }, onProgress, function (scene, message, exception) {
  66401. reject(exception || new Error(message));
  66402. });
  66403. });
  66404. };
  66405. /**
  66406. * Load a scene
  66407. * @param rootUrl a string that defines the root url for scene and resources
  66408. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66409. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66410. * @param onSuccess a callback with the scene when import succeeds
  66411. * @param onProgress a callback with a progress event for each file being loaded
  66412. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66413. * @param pluginExtension the extension used to determine the plugin
  66414. * @returns The loaded plugin
  66415. */
  66416. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66417. if (onSuccess === void 0) { onSuccess = null; }
  66418. if (onProgress === void 0) { onProgress = null; }
  66419. if (onError === void 0) { onError = null; }
  66420. if (pluginExtension === void 0) { pluginExtension = null; }
  66421. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66422. };
  66423. /**
  66424. * Load a scene
  66425. * @param rootUrl a string that defines the root url for scene and resources
  66426. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66427. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66428. * @param onProgress a callback with a progress event for each file being loaded
  66429. * @param pluginExtension the extension used to determine the plugin
  66430. * @returns The loaded scene
  66431. */
  66432. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66433. if (onProgress === void 0) { onProgress = null; }
  66434. if (pluginExtension === void 0) { pluginExtension = null; }
  66435. return new Promise(function (resolve, reject) {
  66436. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66437. resolve(scene);
  66438. }, onProgress, function (scene, message, exception) {
  66439. reject(exception || new Error(message));
  66440. }, pluginExtension);
  66441. });
  66442. };
  66443. /**
  66444. * Append a scene
  66445. * @param rootUrl a string that defines the root url for scene and resources
  66446. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66447. * @param scene is the instance of BABYLON.Scene to append to
  66448. * @param onSuccess a callback with the scene when import succeeds
  66449. * @param onProgress a callback with a progress event for each file being loaded
  66450. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66451. * @param pluginExtension the extension used to determine the plugin
  66452. * @returns The loaded plugin
  66453. */
  66454. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66455. if (onSuccess === void 0) { onSuccess = null; }
  66456. if (onProgress === void 0) { onProgress = null; }
  66457. if (onError === void 0) { onError = null; }
  66458. if (pluginExtension === void 0) { pluginExtension = null; }
  66459. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66460. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66461. return null;
  66462. }
  66463. if (SceneLoader.ShowLoadingScreen) {
  66464. scene.getEngine().displayLoadingUI();
  66465. }
  66466. var loadingToken = {};
  66467. scene._addPendingData(loadingToken);
  66468. var disposeHandler = function () {
  66469. scene._removePendingData(loadingToken);
  66470. scene.getEngine().hideLoadingUI();
  66471. };
  66472. var errorHandler = function (message, exception) {
  66473. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66474. if (onError) {
  66475. onError(scene, errorMessage, exception);
  66476. }
  66477. else {
  66478. BABYLON.Tools.Error(errorMessage);
  66479. // should the exception be thrown?
  66480. }
  66481. disposeHandler();
  66482. };
  66483. var progressHandler = onProgress ? function (event) {
  66484. try {
  66485. onProgress(event);
  66486. }
  66487. catch (e) {
  66488. errorHandler("Error in onProgress callback", e);
  66489. }
  66490. } : undefined;
  66491. var successHandler = function () {
  66492. if (onSuccess) {
  66493. try {
  66494. onSuccess(scene);
  66495. }
  66496. catch (e) {
  66497. errorHandler("Error in onSuccess callback", e);
  66498. }
  66499. }
  66500. scene._removePendingData(loadingToken);
  66501. };
  66502. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66503. if (sceneFilename === "") {
  66504. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66505. }
  66506. if (plugin.load) {
  66507. var syncedPlugin = plugin;
  66508. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66509. return;
  66510. }
  66511. scene.loadingPluginName = plugin.name;
  66512. successHandler();
  66513. }
  66514. else {
  66515. var asyncedPlugin = plugin;
  66516. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66517. scene.loadingPluginName = plugin.name;
  66518. successHandler();
  66519. }).catch(function (error) {
  66520. errorHandler(error.message, error);
  66521. });
  66522. }
  66523. if (SceneLoader.ShowLoadingScreen) {
  66524. scene.executeWhenReady(function () {
  66525. scene.getEngine().hideLoadingUI();
  66526. });
  66527. }
  66528. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66529. };
  66530. /**
  66531. * Append a scene
  66532. * @param rootUrl a string that defines the root url for scene and resources
  66533. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66534. * @param scene is the instance of BABYLON.Scene to append to
  66535. * @param onProgress a callback with a progress event for each file being loaded
  66536. * @param pluginExtension the extension used to determine the plugin
  66537. * @returns The given scene
  66538. */
  66539. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66540. if (onProgress === void 0) { onProgress = null; }
  66541. if (pluginExtension === void 0) { pluginExtension = null; }
  66542. return new Promise(function (resolve, reject) {
  66543. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66544. resolve(scene);
  66545. }, onProgress, function (scene, message, exception) {
  66546. reject(exception || new Error(message));
  66547. }, pluginExtension);
  66548. });
  66549. };
  66550. /**
  66551. * Load a scene into an asset container
  66552. * @param rootUrl a string that defines the root url for scene and resources
  66553. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66554. * @param scene is the instance of BABYLON.Scene to append to
  66555. * @param onSuccess a callback with the scene when import succeeds
  66556. * @param onProgress a callback with a progress event for each file being loaded
  66557. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66558. * @param pluginExtension the extension used to determine the plugin
  66559. * @returns The loaded plugin
  66560. */
  66561. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66562. if (onSuccess === void 0) { onSuccess = null; }
  66563. if (onProgress === void 0) { onProgress = null; }
  66564. if (onError === void 0) { onError = null; }
  66565. if (pluginExtension === void 0) { pluginExtension = null; }
  66566. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66567. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66568. return null;
  66569. }
  66570. var loadingToken = {};
  66571. scene._addPendingData(loadingToken);
  66572. var disposeHandler = function () {
  66573. scene._removePendingData(loadingToken);
  66574. };
  66575. var errorHandler = function (message, exception) {
  66576. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66577. if (onError) {
  66578. onError(scene, errorMessage, exception);
  66579. }
  66580. else {
  66581. BABYLON.Tools.Error(errorMessage);
  66582. // should the exception be thrown?
  66583. }
  66584. disposeHandler();
  66585. };
  66586. var progressHandler = onProgress ? function (event) {
  66587. try {
  66588. onProgress(event);
  66589. }
  66590. catch (e) {
  66591. errorHandler("Error in onProgress callback", e);
  66592. }
  66593. } : undefined;
  66594. var successHandler = function (assets) {
  66595. if (onSuccess) {
  66596. try {
  66597. onSuccess(assets);
  66598. }
  66599. catch (e) {
  66600. errorHandler("Error in onSuccess callback", e);
  66601. }
  66602. }
  66603. scene._removePendingData(loadingToken);
  66604. };
  66605. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66606. if (plugin.loadAssetContainer) {
  66607. var syncedPlugin = plugin;
  66608. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66609. if (!assetContainer) {
  66610. return;
  66611. }
  66612. scene.loadingPluginName = plugin.name;
  66613. successHandler(assetContainer);
  66614. }
  66615. else if (plugin.loadAssetContainerAsync) {
  66616. var asyncedPlugin = plugin;
  66617. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66618. scene.loadingPluginName = plugin.name;
  66619. successHandler(assetContainer);
  66620. }).catch(function (error) {
  66621. errorHandler(error.message, error);
  66622. });
  66623. }
  66624. else {
  66625. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66626. }
  66627. if (SceneLoader.ShowLoadingScreen) {
  66628. scene.executeWhenReady(function () {
  66629. scene.getEngine().hideLoadingUI();
  66630. });
  66631. }
  66632. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66633. };
  66634. /**
  66635. * Load a scene into an asset container
  66636. * @param rootUrl a string that defines the root url for scene and resources
  66637. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66638. * @param scene is the instance of BABYLON.Scene to append to
  66639. * @param onProgress a callback with a progress event for each file being loaded
  66640. * @param pluginExtension the extension used to determine the plugin
  66641. * @returns The loaded asset container
  66642. */
  66643. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66644. if (onProgress === void 0) { onProgress = null; }
  66645. if (pluginExtension === void 0) { pluginExtension = null; }
  66646. return new Promise(function (resolve, reject) {
  66647. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66648. resolve(assetContainer);
  66649. }, onProgress, function (scene, message, exception) {
  66650. reject(exception || new Error(message));
  66651. }, pluginExtension);
  66652. });
  66653. };
  66654. // Flags
  66655. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66656. SceneLoader._ShowLoadingScreen = true;
  66657. SceneLoader._CleanBoneMatrixWeights = false;
  66658. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66659. // Members
  66660. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66661. SceneLoader._registeredPlugins = {};
  66662. return SceneLoader;
  66663. }());
  66664. BABYLON.SceneLoader = SceneLoader;
  66665. ;
  66666. })(BABYLON || (BABYLON = {}));
  66667. //# sourceMappingURL=babylon.sceneLoader.js.map
  66668. var BABYLON;
  66669. (function (BABYLON) {
  66670. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66671. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66672. var parsedMaterial = parsedData.materials[index];
  66673. if (parsedMaterial.id === id) {
  66674. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66675. }
  66676. }
  66677. return null;
  66678. };
  66679. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66680. for (var i in names) {
  66681. if (mesh.name === names[i]) {
  66682. hierarchyIds.push(mesh.id);
  66683. return true;
  66684. }
  66685. }
  66686. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66687. hierarchyIds.push(mesh.id);
  66688. return true;
  66689. }
  66690. return false;
  66691. };
  66692. var logOperation = function (operation, producer) {
  66693. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66694. };
  66695. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66696. if (addToScene === void 0) { addToScene = false; }
  66697. var container = new BABYLON.AssetContainer(scene);
  66698. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66699. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66700. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66701. // and avoid problems with multiple concurrent .babylon loads.
  66702. var log = "importScene has failed JSON parse";
  66703. try {
  66704. var parsedData = JSON.parse(data);
  66705. log = "";
  66706. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66707. var index;
  66708. var cache;
  66709. // Lights
  66710. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66711. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66712. var parsedLight = parsedData.lights[index];
  66713. var light = BABYLON.Light.Parse(parsedLight, scene);
  66714. if (light) {
  66715. container.lights.push(light);
  66716. log += (index === 0 ? "\n\tLights:" : "");
  66717. log += "\n\t\t" + light.toString(fullDetails);
  66718. }
  66719. }
  66720. }
  66721. // Animations
  66722. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66723. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66724. var parsedAnimation = parsedData.animations[index];
  66725. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66726. scene.animations.push(animation);
  66727. container.animations.push(animation);
  66728. log += (index === 0 ? "\n\tAnimations:" : "");
  66729. log += "\n\t\t" + animation.toString(fullDetails);
  66730. }
  66731. }
  66732. // Materials
  66733. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66734. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66735. var parsedMaterial = parsedData.materials[index];
  66736. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66737. container.materials.push(mat);
  66738. log += (index === 0 ? "\n\tMaterials:" : "");
  66739. log += "\n\t\t" + mat.toString(fullDetails);
  66740. }
  66741. }
  66742. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66743. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66744. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66745. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66746. container.multiMaterials.push(mmat);
  66747. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66748. log += "\n\t\t" + mmat.toString(fullDetails);
  66749. }
  66750. }
  66751. // Morph targets
  66752. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66753. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66754. var managerData = _a[_i];
  66755. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66756. }
  66757. }
  66758. // Skeletons
  66759. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66760. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66761. var parsedSkeleton = parsedData.skeletons[index];
  66762. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66763. container.skeletons.push(skeleton);
  66764. log += (index === 0 ? "\n\tSkeletons:" : "");
  66765. log += "\n\t\t" + skeleton.toString(fullDetails);
  66766. }
  66767. }
  66768. // Geometries
  66769. var geometries = parsedData.geometries;
  66770. if (geometries !== undefined && geometries !== null) {
  66771. var addedGeometry = new Array();
  66772. // Boxes
  66773. var boxes = geometries.boxes;
  66774. if (boxes !== undefined && boxes !== null) {
  66775. for (index = 0, cache = boxes.length; index < cache; index++) {
  66776. var parsedBox = boxes[index];
  66777. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66778. }
  66779. }
  66780. // Spheres
  66781. var spheres = geometries.spheres;
  66782. if (spheres !== undefined && spheres !== null) {
  66783. for (index = 0, cache = spheres.length; index < cache; index++) {
  66784. var parsedSphere = spheres[index];
  66785. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66786. }
  66787. }
  66788. // Cylinders
  66789. var cylinders = geometries.cylinders;
  66790. if (cylinders !== undefined && cylinders !== null) {
  66791. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66792. var parsedCylinder = cylinders[index];
  66793. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66794. }
  66795. }
  66796. // Toruses
  66797. var toruses = geometries.toruses;
  66798. if (toruses !== undefined && toruses !== null) {
  66799. for (index = 0, cache = toruses.length; index < cache; index++) {
  66800. var parsedTorus = toruses[index];
  66801. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66802. }
  66803. }
  66804. // Grounds
  66805. var grounds = geometries.grounds;
  66806. if (grounds !== undefined && grounds !== null) {
  66807. for (index = 0, cache = grounds.length; index < cache; index++) {
  66808. var parsedGround = grounds[index];
  66809. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66810. }
  66811. }
  66812. // Planes
  66813. var planes = geometries.planes;
  66814. if (planes !== undefined && planes !== null) {
  66815. for (index = 0, cache = planes.length; index < cache; index++) {
  66816. var parsedPlane = planes[index];
  66817. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66818. }
  66819. }
  66820. // TorusKnots
  66821. var torusKnots = geometries.torusKnots;
  66822. if (torusKnots !== undefined && torusKnots !== null) {
  66823. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66824. var parsedTorusKnot = torusKnots[index];
  66825. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66826. }
  66827. }
  66828. // VertexData
  66829. var vertexData = geometries.vertexData;
  66830. if (vertexData !== undefined && vertexData !== null) {
  66831. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66832. var parsedVertexData = vertexData[index];
  66833. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66834. }
  66835. }
  66836. addedGeometry.forEach(function (g) {
  66837. if (g) {
  66838. container.geometries.push(g);
  66839. }
  66840. });
  66841. }
  66842. // Transform nodes
  66843. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66844. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66845. var parsedTransformNode = parsedData.transformNodes[index];
  66846. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66847. container.transformNodes.push(node);
  66848. }
  66849. }
  66850. // Meshes
  66851. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66852. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66853. var parsedMesh = parsedData.meshes[index];
  66854. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66855. container.meshes.push(mesh);
  66856. log += (index === 0 ? "\n\tMeshes:" : "");
  66857. log += "\n\t\t" + mesh.toString(fullDetails);
  66858. }
  66859. }
  66860. // Cameras
  66861. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66862. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66863. var parsedCamera = parsedData.cameras[index];
  66864. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66865. container.cameras.push(camera);
  66866. log += (index === 0 ? "\n\tCameras:" : "");
  66867. log += "\n\t\t" + camera.toString(fullDetails);
  66868. }
  66869. }
  66870. // Browsing all the graph to connect the dots
  66871. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66872. var camera = scene.cameras[index];
  66873. if (camera._waitingParentId) {
  66874. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66875. camera._waitingParentId = null;
  66876. }
  66877. }
  66878. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66879. var light_1 = scene.lights[index];
  66880. if (light_1 && light_1._waitingParentId) {
  66881. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66882. light_1._waitingParentId = null;
  66883. }
  66884. }
  66885. // Sounds
  66886. // TODO: add sound
  66887. var loadedSounds = [];
  66888. var loadedSound;
  66889. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66890. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66891. var parsedSound = parsedData.sounds[index];
  66892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66893. if (!parsedSound.url)
  66894. parsedSound.url = parsedSound.name;
  66895. if (!loadedSounds[parsedSound.url]) {
  66896. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66897. loadedSounds[parsedSound.url] = loadedSound;
  66898. container.sounds.push(loadedSound);
  66899. }
  66900. else {
  66901. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66902. }
  66903. }
  66904. else {
  66905. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66906. }
  66907. }
  66908. }
  66909. loadedSounds = [];
  66910. // Connect parents & children and parse actions
  66911. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66912. var transformNode = scene.transformNodes[index];
  66913. if (transformNode._waitingParentId) {
  66914. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66915. transformNode._waitingParentId = null;
  66916. }
  66917. }
  66918. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66919. var mesh = scene.meshes[index];
  66920. if (mesh._waitingParentId) {
  66921. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66922. mesh._waitingParentId = null;
  66923. }
  66924. if (mesh._waitingActions) {
  66925. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66926. mesh._waitingActions = null;
  66927. }
  66928. }
  66929. // freeze world matrix application
  66930. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66931. var currentMesh = scene.meshes[index];
  66932. if (currentMesh._waitingFreezeWorldMatrix) {
  66933. currentMesh.freezeWorldMatrix();
  66934. currentMesh._waitingFreezeWorldMatrix = null;
  66935. }
  66936. else {
  66937. currentMesh.computeWorldMatrix(true);
  66938. }
  66939. }
  66940. // Particles Systems
  66941. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66942. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66943. var parsedParticleSystem = parsedData.particleSystems[index];
  66944. if (parsedParticleSystem.activeParticleCount) {
  66945. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66946. container.particleSystems.push(ps);
  66947. }
  66948. else {
  66949. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66950. container.particleSystems.push(ps);
  66951. }
  66952. }
  66953. }
  66954. // Lens flares
  66955. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66956. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66957. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66958. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66959. container.lensFlareSystems.push(lf);
  66960. }
  66961. }
  66962. // Shadows
  66963. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66964. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66965. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66966. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66967. container.shadowGenerators.push(sg);
  66968. }
  66969. }
  66970. // Lights exclusions / inclusions
  66971. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66972. var light_2 = scene.lights[index];
  66973. // Excluded check
  66974. if (light_2._excludedMeshesIds.length > 0) {
  66975. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66976. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66977. if (excludedMesh) {
  66978. light_2.excludedMeshes.push(excludedMesh);
  66979. }
  66980. }
  66981. light_2._excludedMeshesIds = [];
  66982. }
  66983. // Included check
  66984. if (light_2._includedOnlyMeshesIds.length > 0) {
  66985. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66986. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66987. if (includedOnlyMesh) {
  66988. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66989. }
  66990. }
  66991. light_2._includedOnlyMeshesIds = [];
  66992. }
  66993. }
  66994. // Effect layers
  66995. if (parsedData.effectLayers) {
  66996. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66997. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66998. container.effectLayers.push(effectLayer);
  66999. }
  67000. }
  67001. // Actions (scene)
  67002. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67003. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67004. }
  67005. if (!addToScene) {
  67006. container.removeAllFromScene();
  67007. }
  67008. }
  67009. catch (err) {
  67010. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67011. if (onError) {
  67012. onError(msg, err);
  67013. }
  67014. else {
  67015. BABYLON.Tools.Log(msg);
  67016. throw err;
  67017. }
  67018. }
  67019. finally {
  67020. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67021. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67022. }
  67023. }
  67024. return container;
  67025. };
  67026. BABYLON.SceneLoader.RegisterPlugin({
  67027. name: "babylon.js",
  67028. extensions: ".babylon",
  67029. canDirectLoad: function (data) {
  67030. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67031. return true;
  67032. }
  67033. return false;
  67034. },
  67035. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67036. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67037. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67038. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67039. // and avoid problems with multiple concurrent .babylon loads.
  67040. var log = "importMesh has failed JSON parse";
  67041. try {
  67042. var parsedData = JSON.parse(data);
  67043. log = "";
  67044. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67045. if (!meshesNames) {
  67046. meshesNames = null;
  67047. }
  67048. else if (!Array.isArray(meshesNames)) {
  67049. meshesNames = [meshesNames];
  67050. }
  67051. var hierarchyIds = new Array();
  67052. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67053. var loadedSkeletonsIds = [];
  67054. var loadedMaterialsIds = [];
  67055. var index;
  67056. var cache;
  67057. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67058. var parsedMesh = parsedData.meshes[index];
  67059. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67060. if (meshesNames !== null) {
  67061. // Remove found mesh name from list.
  67062. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67063. }
  67064. //Geometry?
  67065. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67066. //does the file contain geometries?
  67067. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67068. //find the correct geometry and add it to the scene
  67069. var found = false;
  67070. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67071. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67072. return;
  67073. }
  67074. else {
  67075. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67076. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67077. switch (geometryType) {
  67078. case "boxes":
  67079. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67080. break;
  67081. case "spheres":
  67082. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67083. break;
  67084. case "cylinders":
  67085. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67086. break;
  67087. case "toruses":
  67088. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67089. break;
  67090. case "grounds":
  67091. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67092. break;
  67093. case "planes":
  67094. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67095. break;
  67096. case "torusKnots":
  67097. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67098. break;
  67099. case "vertexData":
  67100. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67101. break;
  67102. }
  67103. found = true;
  67104. }
  67105. });
  67106. }
  67107. });
  67108. if (found === false) {
  67109. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67110. }
  67111. }
  67112. }
  67113. // Material ?
  67114. if (parsedMesh.materialId) {
  67115. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67116. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67117. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67118. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67119. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67120. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67121. var subMatId = parsedMultiMaterial.materials[matIndex];
  67122. loadedMaterialsIds.push(subMatId);
  67123. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67124. if (mat) {
  67125. log += "\n\tMaterial " + mat.toString(fullDetails);
  67126. }
  67127. }
  67128. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67129. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67130. if (mmat) {
  67131. materialFound = true;
  67132. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67133. }
  67134. break;
  67135. }
  67136. }
  67137. }
  67138. if (materialFound === false) {
  67139. loadedMaterialsIds.push(parsedMesh.materialId);
  67140. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67141. if (!mat) {
  67142. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67143. }
  67144. else {
  67145. log += "\n\tMaterial " + mat.toString(fullDetails);
  67146. }
  67147. }
  67148. }
  67149. // Skeleton ?
  67150. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67151. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67152. if (skeletonAlreadyLoaded === false) {
  67153. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67154. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67155. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67156. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67157. skeletons.push(skeleton);
  67158. loadedSkeletonsIds.push(parsedSkeleton.id);
  67159. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67160. }
  67161. }
  67162. }
  67163. }
  67164. // Morph targets ?
  67165. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67166. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67167. var managerData = _a[_i];
  67168. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67169. }
  67170. }
  67171. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67172. meshes.push(mesh);
  67173. log += "\n\tMesh " + mesh.toString(fullDetails);
  67174. }
  67175. }
  67176. // Connecting parents
  67177. var currentMesh;
  67178. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67179. currentMesh = scene.meshes[index];
  67180. if (currentMesh._waitingParentId) {
  67181. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67182. currentMesh._waitingParentId = null;
  67183. }
  67184. }
  67185. // freeze and compute world matrix application
  67186. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67187. currentMesh = scene.meshes[index];
  67188. if (currentMesh._waitingFreezeWorldMatrix) {
  67189. currentMesh.freezeWorldMatrix();
  67190. currentMesh._waitingFreezeWorldMatrix = null;
  67191. }
  67192. else {
  67193. currentMesh.computeWorldMatrix(true);
  67194. }
  67195. }
  67196. }
  67197. // Particles
  67198. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67199. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67200. var parsedParticleSystem = parsedData.particleSystems[index];
  67201. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67202. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67203. }
  67204. }
  67205. }
  67206. return true;
  67207. }
  67208. catch (err) {
  67209. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67210. if (onError) {
  67211. onError(msg, err);
  67212. }
  67213. else {
  67214. BABYLON.Tools.Log(msg);
  67215. throw err;
  67216. }
  67217. }
  67218. finally {
  67219. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67220. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67221. }
  67222. }
  67223. return false;
  67224. },
  67225. load: function (scene, data, rootUrl, onError) {
  67226. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67227. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67228. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67229. // and avoid problems with multiple concurrent .babylon loads.
  67230. var log = "importScene has failed JSON parse";
  67231. try {
  67232. var parsedData = JSON.parse(data);
  67233. log = "";
  67234. // Scene
  67235. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67236. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67237. }
  67238. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67239. scene.autoClear = parsedData.autoClear;
  67240. }
  67241. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67242. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67243. }
  67244. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67245. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67246. }
  67247. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67248. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67249. }
  67250. // Fog
  67251. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67252. scene.fogMode = parsedData.fogMode;
  67253. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67254. scene.fogStart = parsedData.fogStart;
  67255. scene.fogEnd = parsedData.fogEnd;
  67256. scene.fogDensity = parsedData.fogDensity;
  67257. log += "\tFog mode for scene: ";
  67258. switch (scene.fogMode) {
  67259. // getters not compiling, so using hardcoded
  67260. case 1:
  67261. log += "exp\n";
  67262. break;
  67263. case 2:
  67264. log += "exp2\n";
  67265. break;
  67266. case 3:
  67267. log += "linear\n";
  67268. break;
  67269. }
  67270. }
  67271. //Physics
  67272. if (parsedData.physicsEnabled) {
  67273. var physicsPlugin;
  67274. if (parsedData.physicsEngine === "cannon") {
  67275. physicsPlugin = new BABYLON.CannonJSPlugin();
  67276. }
  67277. else if (parsedData.physicsEngine === "oimo") {
  67278. physicsPlugin = new BABYLON.OimoJSPlugin();
  67279. }
  67280. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67281. //else - default engine, which is currently oimo
  67282. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67283. scene.enablePhysics(physicsGravity, physicsPlugin);
  67284. }
  67285. // Metadata
  67286. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67287. scene.metadata = parsedData.metadata;
  67288. }
  67289. //collisions, if defined. otherwise, default is true
  67290. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67291. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67292. }
  67293. scene.workerCollisions = !!parsedData.workerCollisions;
  67294. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67295. if (!container) {
  67296. return false;
  67297. }
  67298. if (parsedData.autoAnimate) {
  67299. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67300. }
  67301. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67302. scene.setActiveCameraByID(parsedData.activeCameraID);
  67303. }
  67304. // Environment texture
  67305. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67306. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67307. if (parsedData.createDefaultSkybox === true) {
  67308. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67309. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67310. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67311. }
  67312. }
  67313. // Finish
  67314. return true;
  67315. }
  67316. catch (err) {
  67317. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67318. if (onError) {
  67319. onError(msg, err);
  67320. }
  67321. else {
  67322. BABYLON.Tools.Log(msg);
  67323. throw err;
  67324. }
  67325. }
  67326. finally {
  67327. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67328. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67329. }
  67330. }
  67331. return false;
  67332. },
  67333. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67334. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67335. return container;
  67336. }
  67337. });
  67338. })(BABYLON || (BABYLON = {}));
  67339. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67340. var BABYLON;
  67341. (function (BABYLON) {
  67342. var FilesInput = /** @class */ (function () {
  67343. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67344. this.onProcessFileCallback = function () { return true; };
  67345. this._engine = engine;
  67346. this._currentScene = scene;
  67347. this._sceneLoadedCallback = sceneLoadedCallback;
  67348. this._progressCallback = progressCallback;
  67349. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67350. this._textureLoadingCallback = textureLoadingCallback;
  67351. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67352. this._onReloadCallback = onReloadCallback;
  67353. this._errorCallback = errorCallback;
  67354. }
  67355. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67356. var _this = this;
  67357. if (elementToMonitor) {
  67358. this._elementToMonitor = elementToMonitor;
  67359. this._dragEnterHandler = function (e) { _this.drag(e); };
  67360. this._dragOverHandler = function (e) { _this.drag(e); };
  67361. this._dropHandler = function (e) { _this.drop(e); };
  67362. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67363. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67364. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67365. }
  67366. };
  67367. FilesInput.prototype.dispose = function () {
  67368. if (!this._elementToMonitor) {
  67369. return;
  67370. }
  67371. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67372. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67373. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67374. };
  67375. FilesInput.prototype.renderFunction = function () {
  67376. if (this._additionalRenderLoopLogicCallback) {
  67377. this._additionalRenderLoopLogicCallback();
  67378. }
  67379. if (this._currentScene) {
  67380. if (this._textureLoadingCallback) {
  67381. var remaining = this._currentScene.getWaitingItemsCount();
  67382. if (remaining > 0) {
  67383. this._textureLoadingCallback(remaining);
  67384. }
  67385. }
  67386. this._currentScene.render();
  67387. }
  67388. };
  67389. FilesInput.prototype.drag = function (e) {
  67390. e.stopPropagation();
  67391. e.preventDefault();
  67392. };
  67393. FilesInput.prototype.drop = function (eventDrop) {
  67394. eventDrop.stopPropagation();
  67395. eventDrop.preventDefault();
  67396. this.loadFiles(eventDrop);
  67397. };
  67398. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67399. var _this = this;
  67400. var reader = folder.createReader();
  67401. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67402. reader.readEntries(function (entries) {
  67403. remaining.count += entries.length;
  67404. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67405. var entry = entries_1[_i];
  67406. if (entry.isFile) {
  67407. entry.file(function (file) {
  67408. file.correctName = relativePath + file.name;
  67409. files.push(file);
  67410. if (--remaining.count === 0) {
  67411. callback();
  67412. }
  67413. });
  67414. }
  67415. else if (entry.isDirectory) {
  67416. _this._traverseFolder(entry, files, remaining, callback);
  67417. }
  67418. }
  67419. if (--remaining.count) {
  67420. callback();
  67421. }
  67422. });
  67423. };
  67424. FilesInput.prototype._processFiles = function (files) {
  67425. for (var i = 0; i < files.length; i++) {
  67426. var name = files[i].correctName.toLowerCase();
  67427. var extension = name.split('.').pop();
  67428. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67429. continue;
  67430. }
  67431. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67432. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67433. this._sceneFileToLoad = files[i];
  67434. }
  67435. else {
  67436. FilesInput.FilesToLoad[name] = files[i];
  67437. }
  67438. }
  67439. };
  67440. FilesInput.prototype.loadFiles = function (event) {
  67441. var _this = this;
  67442. if (this._startingProcessingFilesCallback)
  67443. this._startingProcessingFilesCallback();
  67444. // Handling data transfer via drag'n'drop
  67445. if (event && event.dataTransfer && event.dataTransfer.files) {
  67446. this._filesToLoad = event.dataTransfer.files;
  67447. }
  67448. // Handling files from input files
  67449. if (event && event.target && event.target.files) {
  67450. this._filesToLoad = event.target.files;
  67451. }
  67452. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67453. var files_1 = new Array();
  67454. var folders = [];
  67455. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67456. for (var i = 0; i < this._filesToLoad.length; i++) {
  67457. var fileToLoad = this._filesToLoad[i];
  67458. var name_1 = fileToLoad.name.toLowerCase();
  67459. var entry = void 0;
  67460. fileToLoad.correctName = name_1;
  67461. if (items) {
  67462. var item = items[i];
  67463. if (item.getAsEntry) {
  67464. entry = item.getAsEntry();
  67465. }
  67466. else if (item.webkitGetAsEntry) {
  67467. entry = item.webkitGetAsEntry();
  67468. }
  67469. }
  67470. if (!entry) {
  67471. files_1.push(fileToLoad);
  67472. }
  67473. else {
  67474. if (entry.isDirectory) {
  67475. folders.push(entry);
  67476. }
  67477. else {
  67478. files_1.push(fileToLoad);
  67479. }
  67480. }
  67481. }
  67482. if (folders.length === 0) {
  67483. this._processFiles(files_1);
  67484. this._processReload();
  67485. }
  67486. else {
  67487. var remaining = { count: folders.length };
  67488. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67489. var folder = folders_1[_i];
  67490. this._traverseFolder(folder, files_1, remaining, function () {
  67491. _this._processFiles(files_1);
  67492. if (remaining.count === 0) {
  67493. _this._processReload();
  67494. }
  67495. });
  67496. }
  67497. }
  67498. }
  67499. };
  67500. FilesInput.prototype._processReload = function () {
  67501. if (this._onReloadCallback) {
  67502. this._onReloadCallback(this._sceneFileToLoad);
  67503. }
  67504. else {
  67505. this.reload();
  67506. }
  67507. };
  67508. FilesInput.prototype.reload = function () {
  67509. var _this = this;
  67510. // If a scene file has been provided
  67511. if (this._sceneFileToLoad) {
  67512. if (this._currentScene) {
  67513. if (BABYLON.Tools.errorsCount > 0) {
  67514. BABYLON.Tools.ClearLogCache();
  67515. }
  67516. this._engine.stopRenderLoop();
  67517. this._currentScene.dispose();
  67518. }
  67519. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67520. if (_this._progressCallback) {
  67521. _this._progressCallback(progress);
  67522. }
  67523. }).then(function (scene) {
  67524. _this._currentScene = scene;
  67525. if (_this._sceneLoadedCallback) {
  67526. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67527. }
  67528. // Wait for textures and shaders to be ready
  67529. _this._currentScene.executeWhenReady(function () {
  67530. _this._engine.runRenderLoop(function () {
  67531. _this.renderFunction();
  67532. });
  67533. });
  67534. }).catch(function (error) {
  67535. if (_this._errorCallback) {
  67536. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67537. }
  67538. });
  67539. }
  67540. else {
  67541. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67542. }
  67543. };
  67544. FilesInput.FilesToLoad = {};
  67545. return FilesInput;
  67546. }());
  67547. BABYLON.FilesInput = FilesInput;
  67548. })(BABYLON || (BABYLON = {}));
  67549. //# sourceMappingURL=babylon.filesInput.js.map
  67550. var BABYLON;
  67551. (function (BABYLON) {
  67552. /**
  67553. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67554. * The underlying implementation relies on an associative array to ensure the best performances.
  67555. * The value can be anything including 'null' but except 'undefined'
  67556. */
  67557. var StringDictionary = /** @class */ (function () {
  67558. function StringDictionary() {
  67559. this._count = 0;
  67560. this._data = {};
  67561. }
  67562. /**
  67563. * This will clear this dictionary and copy the content from the 'source' one.
  67564. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67565. * @param source the dictionary to take the content from and copy to this dictionary
  67566. */
  67567. StringDictionary.prototype.copyFrom = function (source) {
  67568. var _this = this;
  67569. this.clear();
  67570. source.forEach(function (t, v) { return _this.add(t, v); });
  67571. };
  67572. /**
  67573. * Get a value based from its key
  67574. * @param key the given key to get the matching value from
  67575. * @return the value if found, otherwise undefined is returned
  67576. */
  67577. StringDictionary.prototype.get = function (key) {
  67578. var val = this._data[key];
  67579. if (val !== undefined) {
  67580. return val;
  67581. }
  67582. return undefined;
  67583. };
  67584. /**
  67585. * Get a value from its key or add it if it doesn't exist.
  67586. * This method will ensure you that a given key/data will be present in the dictionary.
  67587. * @param key the given key to get the matching value from
  67588. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67589. * The factory will only be invoked if there's no data for the given key.
  67590. * @return the value corresponding to the key.
  67591. */
  67592. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67593. var val = this.get(key);
  67594. if (val !== undefined) {
  67595. return val;
  67596. }
  67597. val = factory(key);
  67598. if (val) {
  67599. this.add(key, val);
  67600. }
  67601. return val;
  67602. };
  67603. /**
  67604. * Get a value from its key if present in the dictionary otherwise add it
  67605. * @param key the key to get the value from
  67606. * @param val if there's no such key/value pair in the dictionary add it with this value
  67607. * @return the value corresponding to the key
  67608. */
  67609. StringDictionary.prototype.getOrAdd = function (key, val) {
  67610. var curVal = this.get(key);
  67611. if (curVal !== undefined) {
  67612. return curVal;
  67613. }
  67614. this.add(key, val);
  67615. return val;
  67616. };
  67617. /**
  67618. * Check if there's a given key in the dictionary
  67619. * @param key the key to check for
  67620. * @return true if the key is present, false otherwise
  67621. */
  67622. StringDictionary.prototype.contains = function (key) {
  67623. return this._data[key] !== undefined;
  67624. };
  67625. /**
  67626. * Add a new key and its corresponding value
  67627. * @param key the key to add
  67628. * @param value the value corresponding to the key
  67629. * @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
  67630. */
  67631. StringDictionary.prototype.add = function (key, value) {
  67632. if (this._data[key] !== undefined) {
  67633. return false;
  67634. }
  67635. this._data[key] = value;
  67636. ++this._count;
  67637. return true;
  67638. };
  67639. StringDictionary.prototype.set = function (key, value) {
  67640. if (this._data[key] === undefined) {
  67641. return false;
  67642. }
  67643. this._data[key] = value;
  67644. return true;
  67645. };
  67646. /**
  67647. * Get the element of the given key and remove it from the dictionary
  67648. * @param key
  67649. */
  67650. StringDictionary.prototype.getAndRemove = function (key) {
  67651. var val = this.get(key);
  67652. if (val !== undefined) {
  67653. delete this._data[key];
  67654. --this._count;
  67655. return val;
  67656. }
  67657. return null;
  67658. };
  67659. /**
  67660. * Remove a key/value from the dictionary.
  67661. * @param key the key to remove
  67662. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67663. */
  67664. StringDictionary.prototype.remove = function (key) {
  67665. if (this.contains(key)) {
  67666. delete this._data[key];
  67667. --this._count;
  67668. return true;
  67669. }
  67670. return false;
  67671. };
  67672. /**
  67673. * Clear the whole content of the dictionary
  67674. */
  67675. StringDictionary.prototype.clear = function () {
  67676. this._data = {};
  67677. this._count = 0;
  67678. };
  67679. Object.defineProperty(StringDictionary.prototype, "count", {
  67680. get: function () {
  67681. return this._count;
  67682. },
  67683. enumerable: true,
  67684. configurable: true
  67685. });
  67686. /**
  67687. * Execute a callback on each key/val of the dictionary.
  67688. * Note that you can remove any element in this dictionary in the callback implementation
  67689. * @param callback the callback to execute on a given key/value pair
  67690. */
  67691. StringDictionary.prototype.forEach = function (callback) {
  67692. for (var cur in this._data) {
  67693. var val = this._data[cur];
  67694. callback(cur, val);
  67695. }
  67696. };
  67697. /**
  67698. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67699. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67700. * Note that you can remove any element in this dictionary in the callback implementation
  67701. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67702. */
  67703. StringDictionary.prototype.first = function (callback) {
  67704. for (var cur in this._data) {
  67705. var val = this._data[cur];
  67706. var res = callback(cur, val);
  67707. if (res) {
  67708. return res;
  67709. }
  67710. }
  67711. return null;
  67712. };
  67713. return StringDictionary;
  67714. }());
  67715. BABYLON.StringDictionary = StringDictionary;
  67716. })(BABYLON || (BABYLON = {}));
  67717. //# sourceMappingURL=babylon.stringDictionary.js.map
  67718. var BABYLON;
  67719. (function (BABYLON) {
  67720. var Tags = /** @class */ (function () {
  67721. function Tags() {
  67722. }
  67723. Tags.EnableFor = function (obj) {
  67724. obj._tags = obj._tags || {};
  67725. obj.hasTags = function () {
  67726. return Tags.HasTags(obj);
  67727. };
  67728. obj.addTags = function (tagsString) {
  67729. return Tags.AddTagsTo(obj, tagsString);
  67730. };
  67731. obj.removeTags = function (tagsString) {
  67732. return Tags.RemoveTagsFrom(obj, tagsString);
  67733. };
  67734. obj.matchesTagsQuery = function (tagsQuery) {
  67735. return Tags.MatchesQuery(obj, tagsQuery);
  67736. };
  67737. };
  67738. Tags.DisableFor = function (obj) {
  67739. delete obj._tags;
  67740. delete obj.hasTags;
  67741. delete obj.addTags;
  67742. delete obj.removeTags;
  67743. delete obj.matchesTagsQuery;
  67744. };
  67745. Tags.HasTags = function (obj) {
  67746. if (!obj._tags) {
  67747. return false;
  67748. }
  67749. return !BABYLON.Tools.IsEmpty(obj._tags);
  67750. };
  67751. Tags.GetTags = function (obj, asString) {
  67752. if (asString === void 0) { asString = true; }
  67753. if (!obj._tags) {
  67754. return null;
  67755. }
  67756. if (asString) {
  67757. var tagsArray = [];
  67758. for (var tag in obj._tags) {
  67759. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67760. tagsArray.push(tag);
  67761. }
  67762. }
  67763. return tagsArray.join(" ");
  67764. }
  67765. else {
  67766. return obj._tags;
  67767. }
  67768. };
  67769. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67770. // a tag cannot start with '||', '&&', and '!'
  67771. // it cannot contain whitespaces
  67772. Tags.AddTagsTo = function (obj, tagsString) {
  67773. if (!tagsString) {
  67774. return;
  67775. }
  67776. if (typeof tagsString !== "string") {
  67777. return;
  67778. }
  67779. var tags = tagsString.split(" ");
  67780. tags.forEach(function (tag, index, array) {
  67781. Tags._AddTagTo(obj, tag);
  67782. });
  67783. };
  67784. Tags._AddTagTo = function (obj, tag) {
  67785. tag = tag.trim();
  67786. if (tag === "" || tag === "true" || tag === "false") {
  67787. return;
  67788. }
  67789. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67790. return;
  67791. }
  67792. Tags.EnableFor(obj);
  67793. obj._tags[tag] = true;
  67794. };
  67795. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67796. if (!Tags.HasTags(obj)) {
  67797. return;
  67798. }
  67799. var tags = tagsString.split(" ");
  67800. for (var t in tags) {
  67801. Tags._RemoveTagFrom(obj, tags[t]);
  67802. }
  67803. };
  67804. Tags._RemoveTagFrom = function (obj, tag) {
  67805. delete obj._tags[tag];
  67806. };
  67807. Tags.MatchesQuery = function (obj, tagsQuery) {
  67808. if (tagsQuery === undefined) {
  67809. return true;
  67810. }
  67811. if (tagsQuery === "") {
  67812. return Tags.HasTags(obj);
  67813. }
  67814. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67815. };
  67816. return Tags;
  67817. }());
  67818. BABYLON.Tags = Tags;
  67819. })(BABYLON || (BABYLON = {}));
  67820. //# sourceMappingURL=babylon.tags.js.map
  67821. var BABYLON;
  67822. (function (BABYLON) {
  67823. var AndOrNotEvaluator = /** @class */ (function () {
  67824. function AndOrNotEvaluator() {
  67825. }
  67826. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67827. if (!query.match(/\([^\(\)]*\)/g)) {
  67828. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67829. }
  67830. else {
  67831. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67832. // remove parenthesis
  67833. r = r.slice(1, r.length - 1);
  67834. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67835. });
  67836. }
  67837. if (query === "true") {
  67838. return true;
  67839. }
  67840. if (query === "false") {
  67841. return false;
  67842. }
  67843. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67844. };
  67845. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67846. evaluateCallback = evaluateCallback || (function (r) {
  67847. return r === "true" ? true : false;
  67848. });
  67849. var result;
  67850. var or = parenthesisContent.split("||");
  67851. for (var i in or) {
  67852. if (or.hasOwnProperty(i)) {
  67853. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67854. var and = ori.split("&&");
  67855. if (and.length > 1) {
  67856. for (var j = 0; j < and.length; ++j) {
  67857. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67858. if (andj !== "true" && andj !== "false") {
  67859. if (andj[0] === "!") {
  67860. result = !evaluateCallback(andj.substring(1));
  67861. }
  67862. else {
  67863. result = evaluateCallback(andj);
  67864. }
  67865. }
  67866. else {
  67867. result = andj === "true" ? true : false;
  67868. }
  67869. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  67870. ori = "false";
  67871. break;
  67872. }
  67873. }
  67874. }
  67875. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  67876. result = true;
  67877. break;
  67878. }
  67879. // result equals false (or undefined)
  67880. if (ori !== "true" && ori !== "false") {
  67881. if (ori[0] === "!") {
  67882. result = !evaluateCallback(ori.substring(1));
  67883. }
  67884. else {
  67885. result = evaluateCallback(ori);
  67886. }
  67887. }
  67888. else {
  67889. result = ori === "true" ? true : false;
  67890. }
  67891. }
  67892. }
  67893. // the whole parenthesis scope is replaced by 'true' or 'false'
  67894. return result ? "true" : "false";
  67895. };
  67896. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67897. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67898. // remove whitespaces
  67899. r = r.replace(/[\s]/g, function () { return ""; });
  67900. return r.length % 2 ? "!" : "";
  67901. });
  67902. booleanString = booleanString.trim();
  67903. if (booleanString === "!true") {
  67904. booleanString = "false";
  67905. }
  67906. else if (booleanString === "!false") {
  67907. booleanString = "true";
  67908. }
  67909. return booleanString;
  67910. };
  67911. return AndOrNotEvaluator;
  67912. }());
  67913. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67914. })(BABYLON || (BABYLON = {}));
  67915. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67916. var BABYLON;
  67917. (function (BABYLON) {
  67918. var Database = /** @class */ (function () {
  67919. function Database(urlToScene, callbackManifestChecked) {
  67920. // Handling various flavors of prefixed version of IndexedDB
  67921. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67922. this.callbackManifestChecked = callbackManifestChecked;
  67923. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67924. this.db = null;
  67925. this._enableSceneOffline = false;
  67926. this._enableTexturesOffline = false;
  67927. this.manifestVersionFound = 0;
  67928. this.mustUpdateRessources = false;
  67929. this.hasReachedQuota = false;
  67930. if (!Database.IDBStorageEnabled) {
  67931. this.callbackManifestChecked(true);
  67932. }
  67933. else {
  67934. this.checkManifestFile();
  67935. }
  67936. }
  67937. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67938. get: function () {
  67939. return this._enableSceneOffline;
  67940. },
  67941. enumerable: true,
  67942. configurable: true
  67943. });
  67944. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67945. get: function () {
  67946. return this._enableTexturesOffline;
  67947. },
  67948. enumerable: true,
  67949. configurable: true
  67950. });
  67951. Database.prototype.checkManifestFile = function () {
  67952. var _this = this;
  67953. var noManifestFile = function () {
  67954. _this._enableSceneOffline = false;
  67955. _this._enableTexturesOffline = false;
  67956. _this.callbackManifestChecked(false);
  67957. };
  67958. var timeStampUsed = false;
  67959. var manifestURL = this.currentSceneUrl + ".manifest";
  67960. var xhr = new XMLHttpRequest();
  67961. if (navigator.onLine) {
  67962. // Adding a timestamp to by-pass browsers' cache
  67963. timeStampUsed = true;
  67964. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67965. }
  67966. xhr.open("GET", manifestURL, true);
  67967. xhr.addEventListener("load", function () {
  67968. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67969. try {
  67970. var manifestFile = JSON.parse(xhr.response);
  67971. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67972. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67973. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67974. _this.manifestVersionFound = manifestFile.version;
  67975. }
  67976. if (_this.callbackManifestChecked) {
  67977. _this.callbackManifestChecked(true);
  67978. }
  67979. }
  67980. catch (ex) {
  67981. noManifestFile();
  67982. }
  67983. }
  67984. else {
  67985. noManifestFile();
  67986. }
  67987. }, false);
  67988. xhr.addEventListener("error", function (event) {
  67989. if (timeStampUsed) {
  67990. timeStampUsed = false;
  67991. // Let's retry without the timeStamp
  67992. // It could fail when coupled with HTML5 Offline API
  67993. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67994. xhr.open("GET", retryManifestURL, true);
  67995. xhr.send();
  67996. }
  67997. else {
  67998. noManifestFile();
  67999. }
  68000. }, false);
  68001. try {
  68002. xhr.send();
  68003. }
  68004. catch (ex) {
  68005. BABYLON.Tools.Error("Error on XHR send request.");
  68006. this.callbackManifestChecked(false);
  68007. }
  68008. };
  68009. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68010. var _this = this;
  68011. var handleError = function () {
  68012. _this.isSupported = false;
  68013. if (errorCallback)
  68014. errorCallback();
  68015. };
  68016. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68017. // Your browser doesn't support IndexedDB
  68018. this.isSupported = false;
  68019. if (errorCallback)
  68020. errorCallback();
  68021. }
  68022. else {
  68023. // If the DB hasn't been opened or created yet
  68024. if (!this.db) {
  68025. this.hasReachedQuota = false;
  68026. this.isSupported = true;
  68027. var request = this.idbFactory.open("babylonjs", 1);
  68028. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68029. request.onerror = function (event) {
  68030. handleError();
  68031. };
  68032. // executes when a version change transaction cannot complete due to other active transactions
  68033. request.onblocked = function (event) {
  68034. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68035. handleError();
  68036. };
  68037. // DB has been opened successfully
  68038. request.onsuccess = function (event) {
  68039. _this.db = request.result;
  68040. successCallback();
  68041. };
  68042. // Initialization of the DB. Creating Scenes & Textures stores
  68043. request.onupgradeneeded = function (event) {
  68044. _this.db = (event.target).result;
  68045. if (_this.db) {
  68046. try {
  68047. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68048. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68049. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68050. }
  68051. catch (ex) {
  68052. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68053. handleError();
  68054. }
  68055. }
  68056. };
  68057. }
  68058. // DB has already been created and opened
  68059. else {
  68060. if (successCallback)
  68061. successCallback();
  68062. }
  68063. }
  68064. };
  68065. Database.prototype.loadImageFromDB = function (url, image) {
  68066. var _this = this;
  68067. var completeURL = Database.ReturnFullUrlLocation(url);
  68068. var saveAndLoadImage = function () {
  68069. if (!_this.hasReachedQuota && _this.db !== null) {
  68070. // the texture is not yet in the DB, let's try to save it
  68071. _this._saveImageIntoDBAsync(completeURL, image);
  68072. }
  68073. // If the texture is not in the DB and we've reached the DB quota limit
  68074. // let's load it directly from the web
  68075. else {
  68076. image.src = url;
  68077. }
  68078. };
  68079. if (!this.mustUpdateRessources) {
  68080. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68081. }
  68082. // First time we're download the images or update requested in the manifest file by a version change
  68083. else {
  68084. saveAndLoadImage();
  68085. }
  68086. };
  68087. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68088. if (this.isSupported && this.db !== null) {
  68089. var texture;
  68090. var transaction = this.db.transaction(["textures"]);
  68091. transaction.onabort = function (event) {
  68092. image.src = url;
  68093. };
  68094. transaction.oncomplete = function (event) {
  68095. var blobTextureURL;
  68096. if (texture) {
  68097. var URL = window.URL || window.webkitURL;
  68098. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68099. image.onerror = function () {
  68100. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68101. image.src = url;
  68102. };
  68103. image.src = blobTextureURL;
  68104. }
  68105. else {
  68106. notInDBCallback();
  68107. }
  68108. };
  68109. var getRequest = transaction.objectStore("textures").get(url);
  68110. getRequest.onsuccess = function (event) {
  68111. texture = (event.target).result;
  68112. };
  68113. getRequest.onerror = function (event) {
  68114. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68115. image.src = url;
  68116. };
  68117. }
  68118. else {
  68119. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68120. image.src = url;
  68121. }
  68122. };
  68123. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68124. var _this = this;
  68125. if (this.isSupported) {
  68126. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68127. var generateBlobUrl = function () {
  68128. var blobTextureURL;
  68129. if (blob) {
  68130. var URL = window.URL || window.webkitURL;
  68131. try {
  68132. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68133. }
  68134. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68135. catch (ex) {
  68136. blobTextureURL = URL.createObjectURL(blob);
  68137. }
  68138. }
  68139. if (blobTextureURL) {
  68140. image.src = blobTextureURL;
  68141. }
  68142. };
  68143. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68144. var xhr = new XMLHttpRequest(), blob;
  68145. xhr.open("GET", url, true);
  68146. xhr.responseType = "blob";
  68147. xhr.addEventListener("load", function () {
  68148. if (xhr.status === 200 && _this.db) {
  68149. // Blob as response (XHR2)
  68150. blob = xhr.response;
  68151. var transaction = _this.db.transaction(["textures"], "readwrite");
  68152. // the transaction could abort because of a QuotaExceededError error
  68153. transaction.onabort = function (event) {
  68154. try {
  68155. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68156. var srcElement = (event.srcElement || event.target);
  68157. var error = srcElement.error;
  68158. if (error && error.name === "QuotaExceededError") {
  68159. _this.hasReachedQuota = true;
  68160. }
  68161. }
  68162. catch (ex) { }
  68163. generateBlobUrl();
  68164. };
  68165. transaction.oncomplete = function (event) {
  68166. generateBlobUrl();
  68167. };
  68168. var newTexture = { textureUrl: url, data: blob };
  68169. try {
  68170. // Put the blob into the dabase
  68171. var addRequest = transaction.objectStore("textures").put(newTexture);
  68172. addRequest.onsuccess = function (event) {
  68173. };
  68174. addRequest.onerror = function (event) {
  68175. generateBlobUrl();
  68176. };
  68177. }
  68178. catch (ex) {
  68179. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68180. if (ex.code === 25) {
  68181. Database.IsUASupportingBlobStorage = false;
  68182. }
  68183. image.src = url;
  68184. }
  68185. }
  68186. else {
  68187. image.src = url;
  68188. }
  68189. }, false);
  68190. xhr.addEventListener("error", function (event) {
  68191. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68192. image.src = url;
  68193. }, false);
  68194. xhr.send();
  68195. }
  68196. else {
  68197. image.src = url;
  68198. }
  68199. }
  68200. else {
  68201. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68202. image.src = url;
  68203. }
  68204. };
  68205. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68206. var _this = this;
  68207. var updateVersion = function () {
  68208. // the version is not yet in the DB or we need to update it
  68209. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68210. };
  68211. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68212. };
  68213. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68214. var _this = this;
  68215. if (this.isSupported && this.db) {
  68216. var version;
  68217. try {
  68218. var transaction = this.db.transaction(["versions"]);
  68219. transaction.oncomplete = function (event) {
  68220. if (version) {
  68221. // If the version in the JSON file is > than the version in DB
  68222. if (_this.manifestVersionFound > version.data) {
  68223. _this.mustUpdateRessources = true;
  68224. updateInDBCallback();
  68225. }
  68226. else {
  68227. callback(version.data);
  68228. }
  68229. }
  68230. // version was not found in DB
  68231. else {
  68232. _this.mustUpdateRessources = true;
  68233. updateInDBCallback();
  68234. }
  68235. };
  68236. transaction.onabort = function (event) {
  68237. callback(-1);
  68238. };
  68239. var getRequest = transaction.objectStore("versions").get(url);
  68240. getRequest.onsuccess = function (event) {
  68241. version = (event.target).result;
  68242. };
  68243. getRequest.onerror = function (event) {
  68244. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68245. callback(-1);
  68246. };
  68247. }
  68248. catch (ex) {
  68249. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68250. callback(-1);
  68251. }
  68252. }
  68253. else {
  68254. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68255. callback(-1);
  68256. }
  68257. };
  68258. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68259. var _this = this;
  68260. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68261. try {
  68262. // Open a transaction to the database
  68263. var transaction = this.db.transaction(["versions"], "readwrite");
  68264. // the transaction could abort because of a QuotaExceededError error
  68265. transaction.onabort = function (event) {
  68266. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68267. var error = event.srcElement['error'];
  68268. if (error && error.name === "QuotaExceededError") {
  68269. _this.hasReachedQuota = true;
  68270. }
  68271. }
  68272. catch (ex) { }
  68273. callback(-1);
  68274. };
  68275. transaction.oncomplete = function (event) {
  68276. callback(_this.manifestVersionFound);
  68277. };
  68278. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68279. // Put the scene into the database
  68280. var addRequest = transaction.objectStore("versions").put(newVersion);
  68281. addRequest.onsuccess = function (event) {
  68282. };
  68283. addRequest.onerror = function (event) {
  68284. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68285. };
  68286. }
  68287. catch (ex) {
  68288. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68289. callback(-1);
  68290. }
  68291. }
  68292. else {
  68293. callback(-1);
  68294. }
  68295. };
  68296. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68297. var _this = this;
  68298. var completeUrl = Database.ReturnFullUrlLocation(url);
  68299. var saveAndLoadFile = function () {
  68300. // the scene is not yet in the DB, let's try to save it
  68301. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68302. };
  68303. this._checkVersionFromDB(completeUrl, function (version) {
  68304. if (version !== -1) {
  68305. if (!_this.mustUpdateRessources) {
  68306. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68307. }
  68308. else {
  68309. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68310. }
  68311. }
  68312. else {
  68313. if (errorCallback) {
  68314. errorCallback();
  68315. }
  68316. }
  68317. });
  68318. };
  68319. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68320. if (this.isSupported && this.db) {
  68321. var targetStore;
  68322. if (url.indexOf(".babylon") !== -1) {
  68323. targetStore = "scenes";
  68324. }
  68325. else {
  68326. targetStore = "textures";
  68327. }
  68328. var file;
  68329. var transaction = this.db.transaction([targetStore]);
  68330. transaction.oncomplete = function (event) {
  68331. if (file) {
  68332. callback(file.data);
  68333. }
  68334. // file was not found in DB
  68335. else {
  68336. notInDBCallback();
  68337. }
  68338. };
  68339. transaction.onabort = function (event) {
  68340. notInDBCallback();
  68341. };
  68342. var getRequest = transaction.objectStore(targetStore).get(url);
  68343. getRequest.onsuccess = function (event) {
  68344. file = (event.target).result;
  68345. };
  68346. getRequest.onerror = function (event) {
  68347. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68348. notInDBCallback();
  68349. };
  68350. }
  68351. else {
  68352. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68353. callback();
  68354. }
  68355. };
  68356. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68357. var _this = this;
  68358. if (this.isSupported) {
  68359. var targetStore;
  68360. if (url.indexOf(".babylon") !== -1) {
  68361. targetStore = "scenes";
  68362. }
  68363. else {
  68364. targetStore = "textures";
  68365. }
  68366. // Create XHR
  68367. var xhr = new XMLHttpRequest();
  68368. var fileData;
  68369. xhr.open("GET", url, true);
  68370. if (useArrayBuffer) {
  68371. xhr.responseType = "arraybuffer";
  68372. }
  68373. if (progressCallback) {
  68374. xhr.onprogress = progressCallback;
  68375. }
  68376. xhr.addEventListener("load", function () {
  68377. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68378. // Blob as response (XHR2)
  68379. //fileData = xhr.responseText;
  68380. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68381. if (!_this.hasReachedQuota && _this.db) {
  68382. // Open a transaction to the database
  68383. var transaction = _this.db.transaction([targetStore], "readwrite");
  68384. // the transaction could abort because of a QuotaExceededError error
  68385. transaction.onabort = function (event) {
  68386. try {
  68387. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68388. var error = event.srcElement['error'];
  68389. if (error && error.name === "QuotaExceededError") {
  68390. _this.hasReachedQuota = true;
  68391. }
  68392. }
  68393. catch (ex) { }
  68394. callback(fileData);
  68395. };
  68396. transaction.oncomplete = function (event) {
  68397. callback(fileData);
  68398. };
  68399. var newFile;
  68400. if (targetStore === "scenes") {
  68401. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68402. }
  68403. else {
  68404. newFile = { textureUrl: url, data: fileData };
  68405. }
  68406. try {
  68407. // Put the scene into the database
  68408. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68409. addRequest.onsuccess = function (event) {
  68410. };
  68411. addRequest.onerror = function (event) {
  68412. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68413. };
  68414. }
  68415. catch (ex) {
  68416. callback(fileData);
  68417. }
  68418. }
  68419. else {
  68420. callback(fileData);
  68421. }
  68422. }
  68423. else {
  68424. callback();
  68425. }
  68426. }, false);
  68427. xhr.addEventListener("error", function (event) {
  68428. BABYLON.Tools.Error("error on XHR request.");
  68429. callback();
  68430. }, false);
  68431. xhr.send();
  68432. }
  68433. else {
  68434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68435. callback();
  68436. }
  68437. };
  68438. Database.IsUASupportingBlobStorage = true;
  68439. Database.IDBStorageEnabled = true;
  68440. Database.parseURL = function (url) {
  68441. var a = document.createElement('a');
  68442. a.href = url;
  68443. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68444. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68445. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68446. return absLocation;
  68447. };
  68448. Database.ReturnFullUrlLocation = function (url) {
  68449. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68450. return (Database.parseURL(window.location.href) + url);
  68451. }
  68452. else {
  68453. return url;
  68454. }
  68455. };
  68456. return Database;
  68457. }());
  68458. BABYLON.Database = Database;
  68459. })(BABYLON || (BABYLON = {}));
  68460. //# sourceMappingURL=babylon.database.js.map
  68461. var BABYLON;
  68462. (function (BABYLON) {
  68463. var FresnelParameters = /** @class */ (function () {
  68464. function FresnelParameters() {
  68465. this._isEnabled = true;
  68466. this.leftColor = BABYLON.Color3.White();
  68467. this.rightColor = BABYLON.Color3.Black();
  68468. this.bias = 0;
  68469. this.power = 1;
  68470. }
  68471. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68472. get: function () {
  68473. return this._isEnabled;
  68474. },
  68475. set: function (value) {
  68476. if (this._isEnabled === value) {
  68477. return;
  68478. }
  68479. this._isEnabled = value;
  68480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68481. },
  68482. enumerable: true,
  68483. configurable: true
  68484. });
  68485. FresnelParameters.prototype.clone = function () {
  68486. var newFresnelParameters = new FresnelParameters();
  68487. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68488. return newFresnelParameters;
  68489. };
  68490. FresnelParameters.prototype.serialize = function () {
  68491. var serializationObject = {};
  68492. serializationObject.isEnabled = this.isEnabled;
  68493. serializationObject.leftColor = this.leftColor.asArray();
  68494. serializationObject.rightColor = this.rightColor.asArray();
  68495. serializationObject.bias = this.bias;
  68496. serializationObject.power = this.power;
  68497. return serializationObject;
  68498. };
  68499. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68500. var fresnelParameters = new FresnelParameters();
  68501. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68502. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68503. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68504. fresnelParameters.bias = parsedFresnelParameters.bias;
  68505. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68506. return fresnelParameters;
  68507. };
  68508. return FresnelParameters;
  68509. }());
  68510. BABYLON.FresnelParameters = FresnelParameters;
  68511. })(BABYLON || (BABYLON = {}));
  68512. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68513. var BABYLON;
  68514. (function (BABYLON) {
  68515. var MultiMaterial = /** @class */ (function (_super) {
  68516. __extends(MultiMaterial, _super);
  68517. function MultiMaterial(name, scene) {
  68518. var _this = _super.call(this, name, scene, true) || this;
  68519. scene.multiMaterials.push(_this);
  68520. _this.subMaterials = new Array();
  68521. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68522. return _this;
  68523. }
  68524. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68525. get: function () {
  68526. return this._subMaterials;
  68527. },
  68528. set: function (value) {
  68529. this._subMaterials = value;
  68530. this._hookArray(value);
  68531. },
  68532. enumerable: true,
  68533. configurable: true
  68534. });
  68535. MultiMaterial.prototype._hookArray = function (array) {
  68536. var _this = this;
  68537. var oldPush = array.push;
  68538. array.push = function () {
  68539. var items = [];
  68540. for (var _i = 0; _i < arguments.length; _i++) {
  68541. items[_i] = arguments[_i];
  68542. }
  68543. var result = oldPush.apply(array, items);
  68544. _this._markAllSubMeshesAsTexturesDirty();
  68545. return result;
  68546. };
  68547. var oldSplice = array.splice;
  68548. array.splice = function (index, deleteCount) {
  68549. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68550. _this._markAllSubMeshesAsTexturesDirty();
  68551. return deleted;
  68552. };
  68553. };
  68554. // Properties
  68555. MultiMaterial.prototype.getSubMaterial = function (index) {
  68556. if (index < 0 || index >= this.subMaterials.length) {
  68557. return this.getScene().defaultMaterial;
  68558. }
  68559. return this.subMaterials[index];
  68560. };
  68561. MultiMaterial.prototype.getActiveTextures = function () {
  68562. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68563. if (subMaterial) {
  68564. return subMaterial.getActiveTextures();
  68565. }
  68566. else {
  68567. return [];
  68568. }
  68569. }));
  68570. var _a;
  68571. };
  68572. // Methods
  68573. MultiMaterial.prototype.getClassName = function () {
  68574. return "MultiMaterial";
  68575. };
  68576. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68577. for (var index = 0; index < this.subMaterials.length; index++) {
  68578. var subMaterial = this.subMaterials[index];
  68579. if (subMaterial) {
  68580. if (subMaterial.storeEffectOnSubMeshes) {
  68581. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68582. return false;
  68583. }
  68584. continue;
  68585. }
  68586. if (!subMaterial.isReady(mesh)) {
  68587. return false;
  68588. }
  68589. }
  68590. }
  68591. return true;
  68592. };
  68593. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68594. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68595. for (var index = 0; index < this.subMaterials.length; index++) {
  68596. var subMaterial = null;
  68597. var current = this.subMaterials[index];
  68598. if (cloneChildren && current) {
  68599. subMaterial = current.clone(name + "-" + current.name);
  68600. }
  68601. else {
  68602. subMaterial = this.subMaterials[index];
  68603. }
  68604. newMultiMaterial.subMaterials.push(subMaterial);
  68605. }
  68606. return newMultiMaterial;
  68607. };
  68608. MultiMaterial.prototype.serialize = function () {
  68609. var serializationObject = {};
  68610. serializationObject.name = this.name;
  68611. serializationObject.id = this.id;
  68612. if (BABYLON.Tags) {
  68613. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68614. }
  68615. serializationObject.materials = [];
  68616. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68617. var subMat = this.subMaterials[matIndex];
  68618. if (subMat) {
  68619. serializationObject.materials.push(subMat.id);
  68620. }
  68621. else {
  68622. serializationObject.materials.push(null);
  68623. }
  68624. }
  68625. return serializationObject;
  68626. };
  68627. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68628. var scene = this.getScene();
  68629. if (!scene) {
  68630. return;
  68631. }
  68632. var index = scene.multiMaterials.indexOf(this);
  68633. if (index >= 0) {
  68634. scene.multiMaterials.splice(index, 1);
  68635. }
  68636. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68637. };
  68638. return MultiMaterial;
  68639. }(BABYLON.Material));
  68640. BABYLON.MultiMaterial = MultiMaterial;
  68641. })(BABYLON || (BABYLON = {}));
  68642. //# sourceMappingURL=babylon.multiMaterial.js.map
  68643. var BABYLON;
  68644. (function (BABYLON) {
  68645. var FreeCameraTouchInput = /** @class */ (function () {
  68646. function FreeCameraTouchInput() {
  68647. this._offsetX = null;
  68648. this._offsetY = null;
  68649. this._pointerPressed = new Array();
  68650. this.touchAngularSensibility = 200000.0;
  68651. this.touchMoveSensibility = 250.0;
  68652. }
  68653. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68654. var _this = this;
  68655. var previousPosition = null;
  68656. if (this._pointerInput === undefined) {
  68657. this._onLostFocus = function (evt) {
  68658. _this._offsetX = null;
  68659. _this._offsetY = null;
  68660. };
  68661. this._pointerInput = function (p, s) {
  68662. var evt = p.event;
  68663. if (evt.pointerType === "mouse") {
  68664. return;
  68665. }
  68666. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68667. if (!noPreventDefault) {
  68668. evt.preventDefault();
  68669. }
  68670. _this._pointerPressed.push(evt.pointerId);
  68671. if (_this._pointerPressed.length !== 1) {
  68672. return;
  68673. }
  68674. previousPosition = {
  68675. x: evt.clientX,
  68676. y: evt.clientY
  68677. };
  68678. }
  68679. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68680. if (!noPreventDefault) {
  68681. evt.preventDefault();
  68682. }
  68683. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68684. if (index === -1) {
  68685. return;
  68686. }
  68687. _this._pointerPressed.splice(index, 1);
  68688. if (index != 0) {
  68689. return;
  68690. }
  68691. previousPosition = null;
  68692. _this._offsetX = null;
  68693. _this._offsetY = null;
  68694. }
  68695. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68696. if (!noPreventDefault) {
  68697. evt.preventDefault();
  68698. }
  68699. if (!previousPosition) {
  68700. return;
  68701. }
  68702. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68703. if (index != 0) {
  68704. return;
  68705. }
  68706. _this._offsetX = evt.clientX - previousPosition.x;
  68707. _this._offsetY = -(evt.clientY - previousPosition.y);
  68708. }
  68709. };
  68710. }
  68711. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68712. if (this._onLostFocus) {
  68713. element.addEventListener("blur", this._onLostFocus);
  68714. }
  68715. };
  68716. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68717. if (this._pointerInput && element) {
  68718. if (this._observer) {
  68719. this.camera.getScene().onPointerObservable.remove(this._observer);
  68720. this._observer = null;
  68721. }
  68722. if (this._onLostFocus) {
  68723. element.removeEventListener("blur", this._onLostFocus);
  68724. this._onLostFocus = null;
  68725. }
  68726. this._pointerPressed = [];
  68727. this._offsetX = null;
  68728. this._offsetY = null;
  68729. }
  68730. };
  68731. FreeCameraTouchInput.prototype.checkInputs = function () {
  68732. if (this._offsetX && this._offsetY) {
  68733. var camera = this.camera;
  68734. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68735. if (this._pointerPressed.length > 1) {
  68736. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68737. }
  68738. else {
  68739. var speed = camera._computeLocalCameraSpeed();
  68740. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68741. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68742. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68743. }
  68744. }
  68745. };
  68746. FreeCameraTouchInput.prototype.getClassName = function () {
  68747. return "FreeCameraTouchInput";
  68748. };
  68749. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68750. return "touch";
  68751. };
  68752. __decorate([
  68753. BABYLON.serialize()
  68754. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68755. __decorate([
  68756. BABYLON.serialize()
  68757. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68758. return FreeCameraTouchInput;
  68759. }());
  68760. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68761. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. // We're mainly based on the logic defined into the FreeCamera code
  68767. var TouchCamera = /** @class */ (function (_super) {
  68768. __extends(TouchCamera, _super);
  68769. //-- end properties for backward compatibility for inputs
  68770. function TouchCamera(name, position, scene) {
  68771. var _this = _super.call(this, name, position, scene) || this;
  68772. _this.inputs.addTouch();
  68773. _this._setupInputs();
  68774. return _this;
  68775. }
  68776. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68777. //-- Begin properties for backward compatibility for inputs
  68778. get: function () {
  68779. var touch = this.inputs.attached["touch"];
  68780. if (touch)
  68781. return touch.touchAngularSensibility;
  68782. return 0;
  68783. },
  68784. set: function (value) {
  68785. var touch = this.inputs.attached["touch"];
  68786. if (touch)
  68787. touch.touchAngularSensibility = value;
  68788. },
  68789. enumerable: true,
  68790. configurable: true
  68791. });
  68792. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68793. get: function () {
  68794. var touch = this.inputs.attached["touch"];
  68795. if (touch)
  68796. return touch.touchMoveSensibility;
  68797. return 0;
  68798. },
  68799. set: function (value) {
  68800. var touch = this.inputs.attached["touch"];
  68801. if (touch)
  68802. touch.touchMoveSensibility = value;
  68803. },
  68804. enumerable: true,
  68805. configurable: true
  68806. });
  68807. TouchCamera.prototype.getClassName = function () {
  68808. return "TouchCamera";
  68809. };
  68810. TouchCamera.prototype._setupInputs = function () {
  68811. var mouse = this.inputs.attached["mouse"];
  68812. if (mouse) {
  68813. mouse.touchEnabled = false;
  68814. }
  68815. };
  68816. return TouchCamera;
  68817. }(BABYLON.FreeCamera));
  68818. BABYLON.TouchCamera = TouchCamera;
  68819. })(BABYLON || (BABYLON = {}));
  68820. //# sourceMappingURL=babylon.touchCamera.js.map
  68821. var BABYLON;
  68822. (function (BABYLON) {
  68823. var ProceduralTexture = /** @class */ (function (_super) {
  68824. __extends(ProceduralTexture, _super);
  68825. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68826. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68827. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68828. if (isCube === void 0) { isCube = false; }
  68829. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68830. _this.isCube = isCube;
  68831. _this.isEnabled = true;
  68832. _this._currentRefreshId = -1;
  68833. _this._refreshRate = 1;
  68834. _this._vertexBuffers = {};
  68835. _this._uniforms = new Array();
  68836. _this._samplers = new Array();
  68837. _this._textures = {};
  68838. _this._floats = {};
  68839. _this._floatsArrays = {};
  68840. _this._colors3 = {};
  68841. _this._colors4 = {};
  68842. _this._vectors2 = {};
  68843. _this._vectors3 = {};
  68844. _this._matrices = {};
  68845. _this._fallbackTextureUsed = false;
  68846. scene.proceduralTextures.push(_this);
  68847. _this._engine = scene.getEngine();
  68848. _this.name = name;
  68849. _this.isRenderTarget = true;
  68850. _this._size = size;
  68851. _this._generateMipMaps = generateMipMaps;
  68852. _this.setFragment(fragment);
  68853. _this._fallbackTexture = fallbackTexture;
  68854. if (isCube) {
  68855. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68856. _this.setFloat("face", 0);
  68857. }
  68858. else {
  68859. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68860. }
  68861. // VBO
  68862. var vertices = [];
  68863. vertices.push(1, 1);
  68864. vertices.push(-1, 1);
  68865. vertices.push(-1, -1);
  68866. vertices.push(1, -1);
  68867. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68868. _this._createIndexBuffer();
  68869. return _this;
  68870. }
  68871. ProceduralTexture.prototype._createIndexBuffer = function () {
  68872. var engine = this._engine;
  68873. // Indices
  68874. var indices = [];
  68875. indices.push(0);
  68876. indices.push(1);
  68877. indices.push(2);
  68878. indices.push(0);
  68879. indices.push(2);
  68880. indices.push(3);
  68881. this._indexBuffer = engine.createIndexBuffer(indices);
  68882. };
  68883. ProceduralTexture.prototype._rebuild = function () {
  68884. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68885. if (vb) {
  68886. vb._rebuild();
  68887. }
  68888. this._createIndexBuffer();
  68889. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68890. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68891. }
  68892. };
  68893. ProceduralTexture.prototype.reset = function () {
  68894. if (this._effect === undefined) {
  68895. return;
  68896. }
  68897. var engine = this._engine;
  68898. engine._releaseEffect(this._effect);
  68899. };
  68900. ProceduralTexture.prototype.isReady = function () {
  68901. var _this = this;
  68902. var engine = this._engine;
  68903. var shaders;
  68904. if (!this._fragment) {
  68905. return false;
  68906. }
  68907. if (this._fallbackTextureUsed) {
  68908. return true;
  68909. }
  68910. if (this._fragment.fragmentElement !== undefined) {
  68911. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68912. }
  68913. else {
  68914. shaders = { vertex: "procedural", fragment: this._fragment };
  68915. }
  68916. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68917. _this.releaseInternalTexture();
  68918. if (_this._fallbackTexture) {
  68919. _this._texture = _this._fallbackTexture._texture;
  68920. if (_this._texture) {
  68921. _this._texture.incrementReferences();
  68922. }
  68923. }
  68924. _this._fallbackTextureUsed = true;
  68925. });
  68926. return this._effect.isReady();
  68927. };
  68928. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68929. this._currentRefreshId = -1;
  68930. };
  68931. ProceduralTexture.prototype.setFragment = function (fragment) {
  68932. this._fragment = fragment;
  68933. };
  68934. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68935. get: function () {
  68936. return this._refreshRate;
  68937. },
  68938. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68939. set: function (value) {
  68940. this._refreshRate = value;
  68941. this.resetRefreshCounter();
  68942. },
  68943. enumerable: true,
  68944. configurable: true
  68945. });
  68946. ProceduralTexture.prototype._shouldRender = function () {
  68947. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68948. return false;
  68949. }
  68950. if (this._fallbackTextureUsed) {
  68951. return false;
  68952. }
  68953. if (this._currentRefreshId === -1) { // At least render once
  68954. this._currentRefreshId = 1;
  68955. return true;
  68956. }
  68957. if (this.refreshRate === this._currentRefreshId) {
  68958. this._currentRefreshId = 1;
  68959. return true;
  68960. }
  68961. this._currentRefreshId++;
  68962. return false;
  68963. };
  68964. ProceduralTexture.prototype.getRenderSize = function () {
  68965. return this._size;
  68966. };
  68967. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68968. if (this._fallbackTextureUsed) {
  68969. return;
  68970. }
  68971. this.releaseInternalTexture();
  68972. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68973. };
  68974. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68975. if (this._uniforms.indexOf(uniformName) === -1) {
  68976. this._uniforms.push(uniformName);
  68977. }
  68978. };
  68979. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68980. if (this._samplers.indexOf(name) === -1) {
  68981. this._samplers.push(name);
  68982. }
  68983. this._textures[name] = texture;
  68984. return this;
  68985. };
  68986. ProceduralTexture.prototype.setFloat = function (name, value) {
  68987. this._checkUniform(name);
  68988. this._floats[name] = value;
  68989. return this;
  68990. };
  68991. ProceduralTexture.prototype.setFloats = function (name, value) {
  68992. this._checkUniform(name);
  68993. this._floatsArrays[name] = value;
  68994. return this;
  68995. };
  68996. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68997. this._checkUniform(name);
  68998. this._colors3[name] = value;
  68999. return this;
  69000. };
  69001. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69002. this._checkUniform(name);
  69003. this._colors4[name] = value;
  69004. return this;
  69005. };
  69006. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69007. this._checkUniform(name);
  69008. this._vectors2[name] = value;
  69009. return this;
  69010. };
  69011. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69012. this._checkUniform(name);
  69013. this._vectors3[name] = value;
  69014. return this;
  69015. };
  69016. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69017. this._checkUniform(name);
  69018. this._matrices[name] = value;
  69019. return this;
  69020. };
  69021. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69022. var scene = this.getScene();
  69023. if (!scene) {
  69024. return;
  69025. }
  69026. var engine = this._engine;
  69027. // Render
  69028. engine.enableEffect(this._effect);
  69029. engine.setState(false);
  69030. // Texture
  69031. for (var name in this._textures) {
  69032. this._effect.setTexture(name, this._textures[name]);
  69033. }
  69034. // Float
  69035. for (name in this._floats) {
  69036. this._effect.setFloat(name, this._floats[name]);
  69037. }
  69038. // Floats
  69039. for (name in this._floatsArrays) {
  69040. this._effect.setArray(name, this._floatsArrays[name]);
  69041. }
  69042. // Color3
  69043. for (name in this._colors3) {
  69044. this._effect.setColor3(name, this._colors3[name]);
  69045. }
  69046. // Color4
  69047. for (name in this._colors4) {
  69048. var color = this._colors4[name];
  69049. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69050. }
  69051. // Vector2
  69052. for (name in this._vectors2) {
  69053. this._effect.setVector2(name, this._vectors2[name]);
  69054. }
  69055. // Vector3
  69056. for (name in this._vectors3) {
  69057. this._effect.setVector3(name, this._vectors3[name]);
  69058. }
  69059. // Matrix
  69060. for (name in this._matrices) {
  69061. this._effect.setMatrix(name, this._matrices[name]);
  69062. }
  69063. if (!this._texture) {
  69064. return;
  69065. }
  69066. if (this.isCube) {
  69067. for (var face = 0; face < 6; face++) {
  69068. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69069. // VBOs
  69070. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69071. this._effect.setFloat("face", face);
  69072. // Clear
  69073. engine.clear(scene.clearColor, true, true, true);
  69074. // Draw order
  69075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69076. // Mipmaps
  69077. if (face === 5) {
  69078. engine.generateMipMapsForCubemap(this._texture);
  69079. }
  69080. }
  69081. }
  69082. else {
  69083. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69084. // VBOs
  69085. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69086. // Clear
  69087. engine.clear(scene.clearColor, true, true, true);
  69088. // Draw order
  69089. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69090. }
  69091. // Unbind
  69092. engine.unBindFramebuffer(this._texture, this.isCube);
  69093. if (this.onGenerated) {
  69094. this.onGenerated();
  69095. }
  69096. };
  69097. ProceduralTexture.prototype.clone = function () {
  69098. var textureSize = this.getSize();
  69099. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69100. // Base texture
  69101. newTexture.hasAlpha = this.hasAlpha;
  69102. newTexture.level = this.level;
  69103. // RenderTarget Texture
  69104. newTexture.coordinatesMode = this.coordinatesMode;
  69105. return newTexture;
  69106. };
  69107. ProceduralTexture.prototype.dispose = function () {
  69108. var scene = this.getScene();
  69109. if (!scene) {
  69110. return;
  69111. }
  69112. var index = scene.proceduralTextures.indexOf(this);
  69113. if (index >= 0) {
  69114. scene.proceduralTextures.splice(index, 1);
  69115. }
  69116. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69117. if (vertexBuffer) {
  69118. vertexBuffer.dispose();
  69119. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69120. }
  69121. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69122. this._indexBuffer = null;
  69123. }
  69124. _super.prototype.dispose.call(this);
  69125. };
  69126. return ProceduralTexture;
  69127. }(BABYLON.Texture));
  69128. BABYLON.ProceduralTexture = ProceduralTexture;
  69129. })(BABYLON || (BABYLON = {}));
  69130. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69131. var BABYLON;
  69132. (function (BABYLON) {
  69133. var CustomProceduralTexture = /** @class */ (function (_super) {
  69134. __extends(CustomProceduralTexture, _super);
  69135. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69136. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69137. _this._animate = true;
  69138. _this._time = 0;
  69139. _this._texturePath = texturePath;
  69140. //Try to load json
  69141. _this.loadJson(texturePath);
  69142. _this.refreshRate = 1;
  69143. return _this;
  69144. }
  69145. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69146. var _this = this;
  69147. var noConfigFile = function () {
  69148. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69149. try {
  69150. _this.setFragment(_this._texturePath);
  69151. }
  69152. catch (ex) {
  69153. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69154. }
  69155. };
  69156. var configFileUrl = jsonUrl + "/config.json";
  69157. var xhr = new XMLHttpRequest();
  69158. xhr.open("GET", configFileUrl, true);
  69159. xhr.addEventListener("load", function () {
  69160. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69161. try {
  69162. _this._config = JSON.parse(xhr.response);
  69163. _this.updateShaderUniforms();
  69164. _this.updateTextures();
  69165. _this.setFragment(_this._texturePath + "/custom");
  69166. _this._animate = _this._config.animate;
  69167. _this.refreshRate = _this._config.refreshrate;
  69168. }
  69169. catch (ex) {
  69170. noConfigFile();
  69171. }
  69172. }
  69173. else {
  69174. noConfigFile();
  69175. }
  69176. }, false);
  69177. xhr.addEventListener("error", function () {
  69178. noConfigFile();
  69179. }, false);
  69180. try {
  69181. xhr.send();
  69182. }
  69183. catch (ex) {
  69184. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69185. }
  69186. };
  69187. CustomProceduralTexture.prototype.isReady = function () {
  69188. if (!_super.prototype.isReady.call(this)) {
  69189. return false;
  69190. }
  69191. for (var name in this._textures) {
  69192. var texture = this._textures[name];
  69193. if (!texture.isReady()) {
  69194. return false;
  69195. }
  69196. }
  69197. return true;
  69198. };
  69199. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69200. var scene = this.getScene();
  69201. if (this._animate && scene) {
  69202. this._time += scene.getAnimationRatio() * 0.03;
  69203. this.updateShaderUniforms();
  69204. }
  69205. _super.prototype.render.call(this, useCameraPostProcess);
  69206. };
  69207. CustomProceduralTexture.prototype.updateTextures = function () {
  69208. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69209. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69210. }
  69211. };
  69212. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69213. if (this._config) {
  69214. for (var j = 0; j < this._config.uniforms.length; j++) {
  69215. var uniform = this._config.uniforms[j];
  69216. switch (uniform.type) {
  69217. case "float":
  69218. this.setFloat(uniform.name, uniform.value);
  69219. break;
  69220. case "color3":
  69221. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69222. break;
  69223. case "color4":
  69224. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69225. break;
  69226. case "vector2":
  69227. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69228. break;
  69229. case "vector3":
  69230. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69231. break;
  69232. }
  69233. }
  69234. }
  69235. this.setFloat("time", this._time);
  69236. };
  69237. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69238. get: function () {
  69239. return this._animate;
  69240. },
  69241. set: function (value) {
  69242. this._animate = value;
  69243. },
  69244. enumerable: true,
  69245. configurable: true
  69246. });
  69247. return CustomProceduralTexture;
  69248. }(BABYLON.ProceduralTexture));
  69249. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69250. })(BABYLON || (BABYLON = {}));
  69251. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69252. var BABYLON;
  69253. (function (BABYLON) {
  69254. var FreeCameraGamepadInput = /** @class */ (function () {
  69255. function FreeCameraGamepadInput() {
  69256. this.gamepadAngularSensibility = 200;
  69257. this.gamepadMoveSensibility = 40;
  69258. // private members
  69259. this._cameraTransform = BABYLON.Matrix.Identity();
  69260. this._deltaTransform = BABYLON.Vector3.Zero();
  69261. this._vector3 = BABYLON.Vector3.Zero();
  69262. this._vector2 = BABYLON.Vector2.Zero();
  69263. }
  69264. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69265. var _this = this;
  69266. var manager = this.camera.getScene().gamepadManager;
  69267. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69268. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69269. // prioritize XBOX gamepads.
  69270. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69271. _this.gamepad = gamepad;
  69272. }
  69273. }
  69274. });
  69275. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69276. if (_this.gamepad === gamepad) {
  69277. _this.gamepad = null;
  69278. }
  69279. });
  69280. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69281. };
  69282. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69283. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69284. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69285. this.gamepad = null;
  69286. };
  69287. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69288. if (this.gamepad && this.gamepad.leftStick) {
  69289. var camera = this.camera;
  69290. var LSValues = this.gamepad.leftStick;
  69291. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69292. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69293. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69294. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69295. var RSValues = this.gamepad.rightStick;
  69296. if (RSValues) {
  69297. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69298. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69299. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69300. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69301. }
  69302. else {
  69303. RSValues = { x: 0, y: 0 };
  69304. }
  69305. if (!camera.rotationQuaternion) {
  69306. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69307. }
  69308. else {
  69309. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69310. }
  69311. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69312. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69313. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69314. camera.cameraDirection.addInPlace(this._deltaTransform);
  69315. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69316. camera.cameraRotation.addInPlace(this._vector2);
  69317. }
  69318. };
  69319. FreeCameraGamepadInput.prototype.getClassName = function () {
  69320. return "FreeCameraGamepadInput";
  69321. };
  69322. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69323. return "gamepad";
  69324. };
  69325. __decorate([
  69326. BABYLON.serialize()
  69327. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69328. __decorate([
  69329. BABYLON.serialize()
  69330. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69331. return FreeCameraGamepadInput;
  69332. }());
  69333. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69334. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69335. })(BABYLON || (BABYLON = {}));
  69336. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69337. var BABYLON;
  69338. (function (BABYLON) {
  69339. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69340. function ArcRotateCameraGamepadInput() {
  69341. this.gamepadRotationSensibility = 80;
  69342. this.gamepadMoveSensibility = 40;
  69343. }
  69344. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69345. var _this = this;
  69346. var manager = this.camera.getScene().gamepadManager;
  69347. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69348. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69349. // prioritize XBOX gamepads.
  69350. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69351. _this.gamepad = gamepad;
  69352. }
  69353. }
  69354. });
  69355. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69356. if (_this.gamepad === gamepad) {
  69357. _this.gamepad = null;
  69358. }
  69359. });
  69360. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69361. };
  69362. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69363. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69364. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69365. this.gamepad = null;
  69366. };
  69367. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69368. if (this.gamepad) {
  69369. var camera = this.camera;
  69370. var RSValues = this.gamepad.rightStick;
  69371. if (RSValues) {
  69372. if (RSValues.x != 0) {
  69373. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69374. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69375. camera.inertialAlphaOffset += normalizedRX;
  69376. }
  69377. }
  69378. if (RSValues.y != 0) {
  69379. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69380. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69381. camera.inertialBetaOffset += normalizedRY;
  69382. }
  69383. }
  69384. }
  69385. var LSValues = this.gamepad.leftStick;
  69386. if (LSValues && LSValues.y != 0) {
  69387. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69388. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69389. this.camera.inertialRadiusOffset -= normalizedLY;
  69390. }
  69391. }
  69392. }
  69393. };
  69394. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69395. return "ArcRotateCameraGamepadInput";
  69396. };
  69397. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69398. return "gamepad";
  69399. };
  69400. __decorate([
  69401. BABYLON.serialize()
  69402. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69403. __decorate([
  69404. BABYLON.serialize()
  69405. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69406. return ArcRotateCameraGamepadInput;
  69407. }());
  69408. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69409. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69410. })(BABYLON || (BABYLON = {}));
  69411. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69412. var BABYLON;
  69413. (function (BABYLON) {
  69414. var GamepadManager = /** @class */ (function () {
  69415. function GamepadManager(_scene) {
  69416. var _this = this;
  69417. this._scene = _scene;
  69418. this._babylonGamepads = [];
  69419. this._oneGamepadConnected = false;
  69420. this._isMonitoring = false;
  69421. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69422. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69423. this._gamepadEventSupported = false;
  69424. }
  69425. else {
  69426. this._gamepadEventSupported = 'GamepadEvent' in window;
  69427. this._gamepadSupport = (navigator.getGamepads ||
  69428. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69429. }
  69430. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69431. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69432. for (var i in _this._babylonGamepads) {
  69433. var gamepad = _this._babylonGamepads[i];
  69434. if (gamepad && gamepad._isConnected) {
  69435. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69436. }
  69437. }
  69438. });
  69439. this._onGamepadConnectedEvent = function (evt) {
  69440. var gamepad = evt.gamepad;
  69441. if (gamepad.index in _this._babylonGamepads) {
  69442. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69443. return;
  69444. }
  69445. }
  69446. var newGamepad;
  69447. if (_this._babylonGamepads[gamepad.index]) {
  69448. newGamepad = _this._babylonGamepads[gamepad.index];
  69449. newGamepad.browserGamepad = gamepad;
  69450. newGamepad._isConnected = true;
  69451. }
  69452. else {
  69453. newGamepad = _this._addNewGamepad(gamepad);
  69454. }
  69455. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69456. _this._startMonitoringGamepads();
  69457. };
  69458. this._onGamepadDisconnectedEvent = function (evt) {
  69459. var gamepad = evt.gamepad;
  69460. // Remove the gamepad from the list of gamepads to monitor.
  69461. for (var i in _this._babylonGamepads) {
  69462. if (_this._babylonGamepads[i].index === gamepad.index) {
  69463. var disconnectedGamepad = _this._babylonGamepads[i];
  69464. disconnectedGamepad._isConnected = false;
  69465. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69466. break;
  69467. }
  69468. }
  69469. };
  69470. if (this._gamepadSupport) {
  69471. //first add already-connected gamepads
  69472. this._updateGamepadObjects();
  69473. if (this._babylonGamepads.length) {
  69474. this._startMonitoringGamepads();
  69475. }
  69476. // Checking if the gamepad connected event is supported (like in Firefox)
  69477. if (this._gamepadEventSupported) {
  69478. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69479. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69480. }
  69481. else {
  69482. this._startMonitoringGamepads();
  69483. }
  69484. }
  69485. }
  69486. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69487. get: function () {
  69488. return this._babylonGamepads;
  69489. },
  69490. enumerable: true,
  69491. configurable: true
  69492. });
  69493. GamepadManager.prototype.getGamepadByType = function (type) {
  69494. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69495. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69496. var gamepad = _a[_i];
  69497. if (gamepad && gamepad.type === type) {
  69498. return gamepad;
  69499. }
  69500. }
  69501. return null;
  69502. };
  69503. GamepadManager.prototype.dispose = function () {
  69504. if (this._gamepadEventSupported) {
  69505. if (this._onGamepadConnectedEvent) {
  69506. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69507. }
  69508. if (this._onGamepadDisconnectedEvent) {
  69509. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69510. }
  69511. this._onGamepadConnectedEvent = null;
  69512. this._onGamepadDisconnectedEvent = null;
  69513. }
  69514. this._babylonGamepads.forEach(function (gamepad) {
  69515. gamepad.dispose();
  69516. });
  69517. this.onGamepadConnectedObservable.clear();
  69518. this.onGamepadDisconnectedObservable.clear();
  69519. this._oneGamepadConnected = false;
  69520. this._stopMonitoringGamepads();
  69521. this._babylonGamepads = [];
  69522. };
  69523. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69524. if (!this._oneGamepadConnected) {
  69525. this._oneGamepadConnected = true;
  69526. }
  69527. var newGamepad;
  69528. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69529. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69530. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69531. }
  69532. // if pose is supported, use the (WebVR) pose enabled controller
  69533. else if (gamepad.pose) {
  69534. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69535. }
  69536. else {
  69537. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69538. }
  69539. this._babylonGamepads[newGamepad.index] = newGamepad;
  69540. return newGamepad;
  69541. };
  69542. GamepadManager.prototype._startMonitoringGamepads = function () {
  69543. if (!this._isMonitoring) {
  69544. this._isMonitoring = true;
  69545. //back-comp
  69546. if (!this._scene) {
  69547. this._checkGamepadsStatus();
  69548. }
  69549. }
  69550. };
  69551. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69552. this._isMonitoring = false;
  69553. };
  69554. GamepadManager.prototype._checkGamepadsStatus = function () {
  69555. var _this = this;
  69556. // Hack to be compatible Chrome
  69557. this._updateGamepadObjects();
  69558. for (var i in this._babylonGamepads) {
  69559. var gamepad = this._babylonGamepads[i];
  69560. if (!gamepad || !gamepad.isConnected) {
  69561. continue;
  69562. }
  69563. gamepad.update();
  69564. }
  69565. if (this._isMonitoring && !this._scene) {
  69566. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69567. }
  69568. };
  69569. // This function is called only on Chrome, which does not properly support
  69570. // connection/disconnection events and forces you to recopy again the gamepad object
  69571. GamepadManager.prototype._updateGamepadObjects = function () {
  69572. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69573. for (var i = 0; i < gamepads.length; i++) {
  69574. var gamepad = gamepads[i];
  69575. if (gamepad) {
  69576. if (!this._babylonGamepads[gamepad.index]) {
  69577. var newGamepad = this._addNewGamepad(gamepad);
  69578. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69579. }
  69580. else {
  69581. // Forced to copy again this object for Chrome for unknown reason
  69582. this._babylonGamepads[i].browserGamepad = gamepad;
  69583. if (!this._babylonGamepads[i].isConnected) {
  69584. this._babylonGamepads[i]._isConnected = true;
  69585. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69586. }
  69587. }
  69588. }
  69589. }
  69590. };
  69591. return GamepadManager;
  69592. }());
  69593. BABYLON.GamepadManager = GamepadManager;
  69594. })(BABYLON || (BABYLON = {}));
  69595. //# sourceMappingURL=babylon.gamepadManager.js.map
  69596. var BABYLON;
  69597. (function (BABYLON) {
  69598. var StickValues = /** @class */ (function () {
  69599. function StickValues(x, y) {
  69600. this.x = x;
  69601. this.y = y;
  69602. }
  69603. return StickValues;
  69604. }());
  69605. BABYLON.StickValues = StickValues;
  69606. var Gamepad = /** @class */ (function () {
  69607. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69608. if (leftStickX === void 0) { leftStickX = 0; }
  69609. if (leftStickY === void 0) { leftStickY = 1; }
  69610. if (rightStickX === void 0) { rightStickX = 2; }
  69611. if (rightStickY === void 0) { rightStickY = 3; }
  69612. this.id = id;
  69613. this.index = index;
  69614. this.browserGamepad = browserGamepad;
  69615. this._isConnected = true;
  69616. this._invertLeftStickY = false;
  69617. this.type = Gamepad.GAMEPAD;
  69618. this._leftStickAxisX = leftStickX;
  69619. this._leftStickAxisY = leftStickY;
  69620. this._rightStickAxisX = rightStickX;
  69621. this._rightStickAxisY = rightStickY;
  69622. if (this.browserGamepad.axes.length >= 2) {
  69623. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69624. }
  69625. if (this.browserGamepad.axes.length >= 4) {
  69626. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69627. }
  69628. }
  69629. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69630. get: function () {
  69631. return this._isConnected;
  69632. },
  69633. enumerable: true,
  69634. configurable: true
  69635. });
  69636. Gamepad.prototype.onleftstickchanged = function (callback) {
  69637. this._onleftstickchanged = callback;
  69638. };
  69639. Gamepad.prototype.onrightstickchanged = function (callback) {
  69640. this._onrightstickchanged = callback;
  69641. };
  69642. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69643. get: function () {
  69644. return this._leftStick;
  69645. },
  69646. set: function (newValues) {
  69647. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69648. this._onleftstickchanged(newValues);
  69649. }
  69650. this._leftStick = newValues;
  69651. },
  69652. enumerable: true,
  69653. configurable: true
  69654. });
  69655. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69656. get: function () {
  69657. return this._rightStick;
  69658. },
  69659. set: function (newValues) {
  69660. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69661. this._onrightstickchanged(newValues);
  69662. }
  69663. this._rightStick = newValues;
  69664. },
  69665. enumerable: true,
  69666. configurable: true
  69667. });
  69668. Gamepad.prototype.update = function () {
  69669. if (this._leftStick) {
  69670. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69671. if (this._invertLeftStickY) {
  69672. this.leftStick.y *= -1;
  69673. }
  69674. }
  69675. if (this._rightStick) {
  69676. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69677. }
  69678. };
  69679. Gamepad.prototype.dispose = function () {
  69680. };
  69681. Gamepad.GAMEPAD = 0;
  69682. Gamepad.GENERIC = 1;
  69683. Gamepad.XBOX = 2;
  69684. Gamepad.POSE_ENABLED = 3;
  69685. return Gamepad;
  69686. }());
  69687. BABYLON.Gamepad = Gamepad;
  69688. var GenericPad = /** @class */ (function (_super) {
  69689. __extends(GenericPad, _super);
  69690. function GenericPad(id, index, browserGamepad) {
  69691. var _this = _super.call(this, id, index, browserGamepad) || this;
  69692. _this.onButtonDownObservable = new BABYLON.Observable();
  69693. _this.onButtonUpObservable = new BABYLON.Observable();
  69694. _this.type = Gamepad.GENERIC;
  69695. _this._buttons = new Array(browserGamepad.buttons.length);
  69696. return _this;
  69697. }
  69698. GenericPad.prototype.onbuttondown = function (callback) {
  69699. this._onbuttondown = callback;
  69700. };
  69701. GenericPad.prototype.onbuttonup = function (callback) {
  69702. this._onbuttonup = callback;
  69703. };
  69704. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69705. if (newValue !== currentValue) {
  69706. if (newValue === 1) {
  69707. if (this._onbuttondown) {
  69708. this._onbuttondown(buttonIndex);
  69709. }
  69710. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69711. }
  69712. if (newValue === 0) {
  69713. if (this._onbuttonup) {
  69714. this._onbuttonup(buttonIndex);
  69715. }
  69716. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69717. }
  69718. }
  69719. return newValue;
  69720. };
  69721. GenericPad.prototype.update = function () {
  69722. _super.prototype.update.call(this);
  69723. for (var index = 0; index < this._buttons.length; index++) {
  69724. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69725. }
  69726. };
  69727. GenericPad.prototype.dispose = function () {
  69728. _super.prototype.dispose.call(this);
  69729. this.onButtonDownObservable.clear();
  69730. this.onButtonUpObservable.clear();
  69731. };
  69732. return GenericPad;
  69733. }(Gamepad));
  69734. BABYLON.GenericPad = GenericPad;
  69735. })(BABYLON || (BABYLON = {}));
  69736. //# sourceMappingURL=babylon.gamepad.js.map
  69737. var BABYLON;
  69738. (function (BABYLON) {
  69739. /**
  69740. * Defines supported buttons for XBox360 compatible gamepads
  69741. */
  69742. var Xbox360Button;
  69743. (function (Xbox360Button) {
  69744. /** A */
  69745. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69746. /** B */
  69747. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69748. /** X */
  69749. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69750. /** Y */
  69751. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69752. /** Start */
  69753. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69754. /** Back */
  69755. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69756. /** Left button */
  69757. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69758. /** Right button */
  69759. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69760. /** Left stick */
  69761. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69762. /** Right stick */
  69763. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69764. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69765. /** Defines values for XBox360 DPad */
  69766. var Xbox360Dpad;
  69767. (function (Xbox360Dpad) {
  69768. /** Up */
  69769. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69770. /** Down */
  69771. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69772. /** Left */
  69773. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69774. /** Right */
  69775. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69776. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69777. /**
  69778. * Defines a XBox360 gamepad
  69779. */
  69780. var Xbox360Pad = /** @class */ (function (_super) {
  69781. __extends(Xbox360Pad, _super);
  69782. /**
  69783. * Creates a new XBox360 gamepad object
  69784. * @param id defines the id of this gamepad
  69785. * @param index defines its index
  69786. * @param gamepad defines the internal HTML gamepad object
  69787. * @param xboxOne defines if it is a XBox One gamepad
  69788. */
  69789. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69790. if (xboxOne === void 0) { xboxOne = false; }
  69791. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69792. _this._leftTrigger = 0;
  69793. _this._rightTrigger = 0;
  69794. /** Observable raised when a button is pressed */
  69795. _this.onButtonDownObservable = new BABYLON.Observable();
  69796. /** Observable raised when a button is released */
  69797. _this.onButtonUpObservable = new BABYLON.Observable();
  69798. /** Observable raised when a pad is pressed */
  69799. _this.onPadDownObservable = new BABYLON.Observable();
  69800. /** Observable raised when a pad is released */
  69801. _this.onPadUpObservable = new BABYLON.Observable();
  69802. _this._buttonA = 0;
  69803. _this._buttonB = 0;
  69804. _this._buttonX = 0;
  69805. _this._buttonY = 0;
  69806. _this._buttonBack = 0;
  69807. _this._buttonStart = 0;
  69808. _this._buttonLB = 0;
  69809. _this._buttonRB = 0;
  69810. _this._buttonLeftStick = 0;
  69811. _this._buttonRightStick = 0;
  69812. _this._dPadUp = 0;
  69813. _this._dPadDown = 0;
  69814. _this._dPadLeft = 0;
  69815. _this._dPadRight = 0;
  69816. _this._isXboxOnePad = false;
  69817. _this.type = BABYLON.Gamepad.XBOX;
  69818. _this._isXboxOnePad = xboxOne;
  69819. return _this;
  69820. }
  69821. /**
  69822. * Defines the callback to call when left trigger is pressed
  69823. * @param callback defines the callback to use
  69824. */
  69825. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69826. this._onlefttriggerchanged = callback;
  69827. };
  69828. /**
  69829. * Defines the callback to call when right trigger is pressed
  69830. * @param callback defines the callback to use
  69831. */
  69832. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69833. this._onrighttriggerchanged = callback;
  69834. };
  69835. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69836. /**
  69837. * Gets or sets left trigger value
  69838. */
  69839. get: function () {
  69840. return this._leftTrigger;
  69841. },
  69842. set: function (newValue) {
  69843. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69844. this._onlefttriggerchanged(newValue);
  69845. }
  69846. this._leftTrigger = newValue;
  69847. },
  69848. enumerable: true,
  69849. configurable: true
  69850. });
  69851. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69852. /**
  69853. * Gets or sets right trigger value
  69854. */
  69855. get: function () {
  69856. return this._rightTrigger;
  69857. },
  69858. set: function (newValue) {
  69859. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69860. this._onrighttriggerchanged(newValue);
  69861. }
  69862. this._rightTrigger = newValue;
  69863. },
  69864. enumerable: true,
  69865. configurable: true
  69866. });
  69867. /**
  69868. * Defines the callback to call when a button is pressed
  69869. * @param callback defines the callback to use
  69870. */
  69871. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69872. this._onbuttondown = callback;
  69873. };
  69874. /**
  69875. * Defines the callback to call when a button is released
  69876. * @param callback defines the callback to use
  69877. */
  69878. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69879. this._onbuttonup = callback;
  69880. };
  69881. /**
  69882. * Defines the callback to call when a pad is pressed
  69883. * @param callback defines the callback to use
  69884. */
  69885. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69886. this._ondpaddown = callback;
  69887. };
  69888. /**
  69889. * Defines the callback to call when a pad is released
  69890. * @param callback defines the callback to use
  69891. */
  69892. Xbox360Pad.prototype.ondpadup = function (callback) {
  69893. this._ondpadup = callback;
  69894. };
  69895. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69896. if (newValue !== currentValue) {
  69897. if (newValue === 1) {
  69898. if (this._onbuttondown) {
  69899. this._onbuttondown(buttonType);
  69900. }
  69901. this.onButtonDownObservable.notifyObservers(buttonType);
  69902. }
  69903. if (newValue === 0) {
  69904. if (this._onbuttonup) {
  69905. this._onbuttonup(buttonType);
  69906. }
  69907. this.onButtonUpObservable.notifyObservers(buttonType);
  69908. }
  69909. }
  69910. return newValue;
  69911. };
  69912. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69913. if (newValue !== currentValue) {
  69914. if (newValue === 1) {
  69915. if (this._ondpaddown) {
  69916. this._ondpaddown(buttonType);
  69917. }
  69918. this.onPadDownObservable.notifyObservers(buttonType);
  69919. }
  69920. if (newValue === 0) {
  69921. if (this._ondpadup) {
  69922. this._ondpadup(buttonType);
  69923. }
  69924. this.onPadUpObservable.notifyObservers(buttonType);
  69925. }
  69926. }
  69927. return newValue;
  69928. };
  69929. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69930. /** Gets or sets value of A button */
  69931. get: function () {
  69932. return this._buttonA;
  69933. },
  69934. set: function (value) {
  69935. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69936. },
  69937. enumerable: true,
  69938. configurable: true
  69939. });
  69940. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69941. /** Gets or sets value of B button */
  69942. get: function () {
  69943. return this._buttonB;
  69944. },
  69945. set: function (value) {
  69946. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69947. },
  69948. enumerable: true,
  69949. configurable: true
  69950. });
  69951. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69952. /** Gets or sets value of X button */
  69953. get: function () {
  69954. return this._buttonX;
  69955. },
  69956. set: function (value) {
  69957. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69958. },
  69959. enumerable: true,
  69960. configurable: true
  69961. });
  69962. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69963. /** Gets or sets value of Y button */
  69964. get: function () {
  69965. return this._buttonY;
  69966. },
  69967. set: function (value) {
  69968. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69974. /** Gets or sets value of Start button */
  69975. get: function () {
  69976. return this._buttonStart;
  69977. },
  69978. set: function (value) {
  69979. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69980. },
  69981. enumerable: true,
  69982. configurable: true
  69983. });
  69984. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69985. /** Gets or sets value of Back button */
  69986. get: function () {
  69987. return this._buttonBack;
  69988. },
  69989. set: function (value) {
  69990. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69991. },
  69992. enumerable: true,
  69993. configurable: true
  69994. });
  69995. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69996. /** Gets or sets value of Left button */
  69997. get: function () {
  69998. return this._buttonLB;
  69999. },
  70000. set: function (value) {
  70001. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70002. },
  70003. enumerable: true,
  70004. configurable: true
  70005. });
  70006. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70007. /** Gets or sets value of Right button */
  70008. get: function () {
  70009. return this._buttonRB;
  70010. },
  70011. set: function (value) {
  70012. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70013. },
  70014. enumerable: true,
  70015. configurable: true
  70016. });
  70017. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70018. /** Gets or sets value of left stick */
  70019. get: function () {
  70020. return this._buttonLeftStick;
  70021. },
  70022. set: function (value) {
  70023. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70024. },
  70025. enumerable: true,
  70026. configurable: true
  70027. });
  70028. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70029. /** Gets or sets value of right stick */
  70030. get: function () {
  70031. return this._buttonRightStick;
  70032. },
  70033. set: function (value) {
  70034. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70035. },
  70036. enumerable: true,
  70037. configurable: true
  70038. });
  70039. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70040. /** Gets or sets value of DPad up */
  70041. get: function () {
  70042. return this._dPadUp;
  70043. },
  70044. set: function (value) {
  70045. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70046. },
  70047. enumerable: true,
  70048. configurable: true
  70049. });
  70050. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70051. /** Gets or sets value of DPad down */
  70052. get: function () {
  70053. return this._dPadDown;
  70054. },
  70055. set: function (value) {
  70056. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70062. /** Gets or sets value of DPad left */
  70063. get: function () {
  70064. return this._dPadLeft;
  70065. },
  70066. set: function (value) {
  70067. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70068. },
  70069. enumerable: true,
  70070. configurable: true
  70071. });
  70072. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70073. /** Gets or sets value of DPad right */
  70074. get: function () {
  70075. return this._dPadRight;
  70076. },
  70077. set: function (value) {
  70078. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70079. },
  70080. enumerable: true,
  70081. configurable: true
  70082. });
  70083. /**
  70084. * Force the gamepad to synchronize with device values
  70085. */
  70086. Xbox360Pad.prototype.update = function () {
  70087. _super.prototype.update.call(this);
  70088. if (this._isXboxOnePad) {
  70089. this.buttonA = this.browserGamepad.buttons[0].value;
  70090. this.buttonB = this.browserGamepad.buttons[1].value;
  70091. this.buttonX = this.browserGamepad.buttons[2].value;
  70092. this.buttonY = this.browserGamepad.buttons[3].value;
  70093. this.buttonLB = this.browserGamepad.buttons[4].value;
  70094. this.buttonRB = this.browserGamepad.buttons[5].value;
  70095. this.leftTrigger = this.browserGamepad.axes[2];
  70096. this.rightTrigger = this.browserGamepad.axes[5];
  70097. this.buttonBack = this.browserGamepad.buttons[9].value;
  70098. this.buttonStart = this.browserGamepad.buttons[8].value;
  70099. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70100. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70101. this.dPadUp = this.browserGamepad.buttons[11].value;
  70102. this.dPadDown = this.browserGamepad.buttons[12].value;
  70103. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70104. this.dPadRight = this.browserGamepad.buttons[14].value;
  70105. }
  70106. else {
  70107. this.buttonA = this.browserGamepad.buttons[0].value;
  70108. this.buttonB = this.browserGamepad.buttons[1].value;
  70109. this.buttonX = this.browserGamepad.buttons[2].value;
  70110. this.buttonY = this.browserGamepad.buttons[3].value;
  70111. this.buttonLB = this.browserGamepad.buttons[4].value;
  70112. this.buttonRB = this.browserGamepad.buttons[5].value;
  70113. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70114. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70115. this.buttonBack = this.browserGamepad.buttons[8].value;
  70116. this.buttonStart = this.browserGamepad.buttons[9].value;
  70117. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70118. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70119. this.dPadUp = this.browserGamepad.buttons[12].value;
  70120. this.dPadDown = this.browserGamepad.buttons[13].value;
  70121. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70122. this.dPadRight = this.browserGamepad.buttons[15].value;
  70123. }
  70124. };
  70125. Xbox360Pad.prototype.dispose = function () {
  70126. _super.prototype.dispose.call(this);
  70127. this.onButtonDownObservable.clear();
  70128. this.onButtonUpObservable.clear();
  70129. this.onPadDownObservable.clear();
  70130. this.onPadUpObservable.clear();
  70131. };
  70132. return Xbox360Pad;
  70133. }(BABYLON.Gamepad));
  70134. BABYLON.Xbox360Pad = Xbox360Pad;
  70135. })(BABYLON || (BABYLON = {}));
  70136. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70137. var BABYLON;
  70138. (function (BABYLON) {
  70139. /**
  70140. * Defines the types of pose enabled controllers that are supported
  70141. */
  70142. var PoseEnabledControllerType;
  70143. (function (PoseEnabledControllerType) {
  70144. /**
  70145. * HTC Vive
  70146. */
  70147. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70148. /**
  70149. * Oculus Rift
  70150. */
  70151. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70152. /**
  70153. * Windows mixed reality
  70154. */
  70155. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70156. /**
  70157. * Samsung gear VR
  70158. */
  70159. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70160. /**
  70161. * Google Daydream
  70162. */
  70163. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70164. /**
  70165. * Generic
  70166. */
  70167. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70168. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70169. /**
  70170. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70171. */
  70172. var PoseEnabledControllerHelper = /** @class */ (function () {
  70173. function PoseEnabledControllerHelper() {
  70174. }
  70175. /**
  70176. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70177. * @param vrGamepad the gamepad to initialized
  70178. * @returns a vr controller of the type the gamepad identified as
  70179. */
  70180. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70181. // Oculus Touch
  70182. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70183. return new BABYLON.OculusTouchController(vrGamepad);
  70184. }
  70185. // Windows Mixed Reality controllers
  70186. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70187. return new BABYLON.WindowsMotionController(vrGamepad);
  70188. }
  70189. // HTC Vive
  70190. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70191. return new BABYLON.ViveController(vrGamepad);
  70192. }
  70193. // Samsung/Oculus Gear VR
  70194. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70195. return new BABYLON.GearVRController(vrGamepad);
  70196. }
  70197. // Google Daydream
  70198. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70199. return new BABYLON.DaydreamController(vrGamepad);
  70200. }
  70201. // Generic
  70202. else {
  70203. return new BABYLON.GenericController(vrGamepad);
  70204. }
  70205. };
  70206. return PoseEnabledControllerHelper;
  70207. }());
  70208. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70209. /**
  70210. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70211. */
  70212. var PoseEnabledController = /** @class */ (function (_super) {
  70213. __extends(PoseEnabledController, _super);
  70214. /**
  70215. * Creates a new PoseEnabledController from a gamepad
  70216. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70217. */
  70218. function PoseEnabledController(browserGamepad) {
  70219. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70220. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70221. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70222. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70223. /**
  70224. * The device position in babylon space
  70225. */
  70226. _this.devicePosition = BABYLON.Vector3.Zero();
  70227. /**
  70228. * The device rotation in babylon space
  70229. */
  70230. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70231. /**
  70232. * The scale factor of the device in babylon space
  70233. */
  70234. _this.deviceScaleFactor = 1;
  70235. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70236. /**
  70237. * Internal, matrix used to convert room space to babylon space
  70238. */
  70239. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70240. /**
  70241. * Node to be used when casting a ray from the controller
  70242. */
  70243. _this._pointingPoseNode = null;
  70244. _this._workingMatrix = BABYLON.Matrix.Identity();
  70245. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70246. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70247. _this.position = BABYLON.Vector3.Zero();
  70248. _this.rotationQuaternion = new BABYLON.Quaternion();
  70249. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70250. _this._calculatedRotation = new BABYLON.Quaternion();
  70251. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70252. return _this;
  70253. }
  70254. /**
  70255. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70256. */
  70257. PoseEnabledController.prototype.update = function () {
  70258. _super.prototype.update.call(this);
  70259. var pose = this.browserGamepad.pose;
  70260. this.updateFromDevice(pose);
  70261. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70262. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70263. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70264. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70265. if (this._mesh) {
  70266. this._mesh.position.copyFrom(this.devicePosition);
  70267. if (this._mesh.rotationQuaternion) {
  70268. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70269. }
  70270. }
  70271. };
  70272. /**
  70273. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70274. * @param poseData raw pose fromthe device
  70275. */
  70276. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70277. if (poseData) {
  70278. this.rawPose = poseData;
  70279. if (poseData.position) {
  70280. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70281. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70282. this._deviceRoomPosition.z *= -1;
  70283. }
  70284. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70285. this._calculatedPosition.addInPlace(this.position);
  70286. }
  70287. var pose = this.rawPose;
  70288. if (poseData.orientation && pose.orientation) {
  70289. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70290. if (this._mesh) {
  70291. if (this._mesh.getScene().useRightHandedSystem) {
  70292. this._deviceRoomRotationQuaternion.z *= -1;
  70293. this._deviceRoomRotationQuaternion.w *= -1;
  70294. }
  70295. else {
  70296. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70297. }
  70298. }
  70299. // if the camera is set, rotate to the camera's rotation
  70300. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70301. }
  70302. }
  70303. };
  70304. /**
  70305. * Attaches a mesh to the controller
  70306. * @param mesh the mesh to be attached
  70307. */
  70308. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70309. if (this._mesh) {
  70310. this._mesh.parent = null;
  70311. }
  70312. this._mesh = mesh;
  70313. if (this._poseControlledCamera) {
  70314. this._mesh.parent = this._poseControlledCamera;
  70315. }
  70316. if (!this._mesh.rotationQuaternion) {
  70317. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70318. }
  70319. };
  70320. /**
  70321. * Attaches the controllers mesh to a camera
  70322. * @param camera the camera the mesh should be attached to
  70323. */
  70324. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70325. this._poseControlledCamera = camera;
  70326. if (this._mesh) {
  70327. this._mesh.parent = this._poseControlledCamera;
  70328. }
  70329. };
  70330. /**
  70331. * Disposes of the controller
  70332. */
  70333. PoseEnabledController.prototype.dispose = function () {
  70334. if (this._mesh) {
  70335. this._mesh.dispose();
  70336. }
  70337. this._mesh = null;
  70338. _super.prototype.dispose.call(this);
  70339. };
  70340. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70341. /**
  70342. * The mesh that is attached to the controller
  70343. */
  70344. get: function () {
  70345. return this._mesh;
  70346. },
  70347. enumerable: true,
  70348. configurable: true
  70349. });
  70350. /**
  70351. * Gets the ray of the controller in the direction the controller is pointing
  70352. * @param length the length the resulting ray should be
  70353. * @returns a ray in the direction the controller is pointing
  70354. */
  70355. PoseEnabledController.prototype.getForwardRay = function (length) {
  70356. if (length === void 0) { length = 100; }
  70357. if (!this.mesh) {
  70358. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70359. }
  70360. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70361. var origin = m.getTranslation();
  70362. var forward = new BABYLON.Vector3(0, 0, -1);
  70363. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70364. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70365. return new BABYLON.Ray(origin, direction, length);
  70366. };
  70367. /**
  70368. * Name of the child mesh that can be used to cast a ray from the controller
  70369. */
  70370. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70371. return PoseEnabledController;
  70372. }(BABYLON.Gamepad));
  70373. BABYLON.PoseEnabledController = PoseEnabledController;
  70374. })(BABYLON || (BABYLON = {}));
  70375. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70376. var BABYLON;
  70377. (function (BABYLON) {
  70378. /**
  70379. * Defines the WebVRController object that represents controllers tracked in 3D space
  70380. */
  70381. var WebVRController = /** @class */ (function (_super) {
  70382. __extends(WebVRController, _super);
  70383. /**
  70384. * Creates a new WebVRController from a gamepad
  70385. * @param vrGamepad the gamepad that the WebVRController should be created from
  70386. */
  70387. function WebVRController(vrGamepad) {
  70388. var _this = _super.call(this, vrGamepad) || this;
  70389. // Observables
  70390. /**
  70391. * Fired when the trigger state has changed
  70392. */
  70393. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70394. /**
  70395. * Fired when the main button state has changed
  70396. */
  70397. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70398. /**
  70399. * Fired when the secondary button state has changed
  70400. */
  70401. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70402. /**
  70403. * Fired when the pad state has changed
  70404. */
  70405. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70406. /**
  70407. * Fired when controllers stick values have changed
  70408. */
  70409. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70410. /**
  70411. * X and Y axis corrisponding to the controllers joystick
  70412. */
  70413. _this.pad = { x: 0, y: 0 };
  70414. // avoid GC, store state in a tmp object
  70415. _this._changes = {
  70416. pressChanged: false,
  70417. touchChanged: false,
  70418. valueChanged: false,
  70419. changed: false
  70420. };
  70421. _this._buttons = new Array(vrGamepad.buttons.length);
  70422. _this.hand = vrGamepad.hand;
  70423. return _this;
  70424. }
  70425. /**
  70426. * Fired when a controller button's state has changed
  70427. * @param callback the callback containing the button that was modified
  70428. */
  70429. WebVRController.prototype.onButtonStateChange = function (callback) {
  70430. this._onButtonStateChange = callback;
  70431. };
  70432. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70433. /**
  70434. * The default controller model for the controller
  70435. */
  70436. get: function () {
  70437. return this._defaultModel;
  70438. },
  70439. enumerable: true,
  70440. configurable: true
  70441. });
  70442. /**
  70443. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70444. */
  70445. WebVRController.prototype.update = function () {
  70446. _super.prototype.update.call(this);
  70447. for (var index = 0; index < this._buttons.length; index++) {
  70448. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70449. }
  70450. ;
  70451. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70452. this.pad.x = this.leftStick.x;
  70453. this.pad.y = this.leftStick.y;
  70454. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70455. }
  70456. };
  70457. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70458. if (!newState) {
  70459. newState = {
  70460. pressed: false,
  70461. touched: false,
  70462. value: 0
  70463. };
  70464. }
  70465. if (!currentState) {
  70466. this._buttons[buttonIndex] = {
  70467. pressed: newState.pressed,
  70468. touched: newState.touched,
  70469. value: newState.value
  70470. };
  70471. return;
  70472. }
  70473. this._checkChanges(newState, currentState);
  70474. if (this._changes.changed) {
  70475. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70476. this._handleButtonChange(buttonIndex, newState, this._changes);
  70477. }
  70478. this._buttons[buttonIndex].pressed = newState.pressed;
  70479. this._buttons[buttonIndex].touched = newState.touched;
  70480. // oculus triggers are never 0, thou not touched.
  70481. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70482. };
  70483. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70484. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70485. this._changes.touchChanged = newState.touched !== currentState.touched;
  70486. this._changes.valueChanged = newState.value !== currentState.value;
  70487. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70488. return this._changes;
  70489. };
  70490. /**
  70491. * Disposes of th webVRCOntroller
  70492. */
  70493. WebVRController.prototype.dispose = function () {
  70494. _super.prototype.dispose.call(this);
  70495. this.onTriggerStateChangedObservable.clear();
  70496. this.onMainButtonStateChangedObservable.clear();
  70497. this.onSecondaryButtonStateChangedObservable.clear();
  70498. this.onPadStateChangedObservable.clear();
  70499. this.onPadValuesChangedObservable.clear();
  70500. };
  70501. return WebVRController;
  70502. }(BABYLON.PoseEnabledController));
  70503. BABYLON.WebVRController = WebVRController;
  70504. })(BABYLON || (BABYLON = {}));
  70505. //# sourceMappingURL=babylon.webVRController.js.map
  70506. var BABYLON;
  70507. (function (BABYLON) {
  70508. /**
  70509. * Oculus Touch Controller
  70510. */
  70511. var OculusTouchController = /** @class */ (function (_super) {
  70512. __extends(OculusTouchController, _super);
  70513. /**
  70514. * Creates a new OculusTouchController from a gamepad
  70515. * @param vrGamepad the gamepad that the controller should be created from
  70516. */
  70517. function OculusTouchController(vrGamepad) {
  70518. var _this = _super.call(this, vrGamepad) || this;
  70519. /**
  70520. * Fired when the secondary trigger on this controller is modified
  70521. */
  70522. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70523. /**
  70524. * Fired when the thumb rest on this controller is modified
  70525. */
  70526. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70527. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70528. return _this;
  70529. }
  70530. /**
  70531. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70532. * @param scene scene in which to add meshes
  70533. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70534. */
  70535. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70536. var _this = this;
  70537. var meshName;
  70538. // Hand
  70539. if (this.hand === 'left') {
  70540. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70541. }
  70542. else { // Right is the default if no hand is specified
  70543. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70544. }
  70545. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70546. /*
  70547. Parent Mesh name: oculus_touch_left
  70548. - body
  70549. - trigger
  70550. - thumbstick
  70551. - grip
  70552. - button_y
  70553. - button_x
  70554. - button_enter
  70555. */
  70556. _this._defaultModel = newMeshes[1];
  70557. _this.attachToMesh(_this._defaultModel);
  70558. if (meshLoaded) {
  70559. meshLoaded(_this._defaultModel);
  70560. }
  70561. });
  70562. };
  70563. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70564. /**
  70565. * Fired when the A button on this controller is modified
  70566. */
  70567. get: function () {
  70568. if (this.hand === 'right') {
  70569. return this.onMainButtonStateChangedObservable;
  70570. }
  70571. else {
  70572. throw new Error('No A button on left hand');
  70573. }
  70574. },
  70575. enumerable: true,
  70576. configurable: true
  70577. });
  70578. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70579. /**
  70580. * Fired when the B button on this controller is modified
  70581. */
  70582. get: function () {
  70583. if (this.hand === 'right') {
  70584. return this.onSecondaryButtonStateChangedObservable;
  70585. }
  70586. else {
  70587. throw new Error('No B button on left hand');
  70588. }
  70589. },
  70590. enumerable: true,
  70591. configurable: true
  70592. });
  70593. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70594. /**
  70595. * Fired when the X button on this controller is modified
  70596. */
  70597. get: function () {
  70598. if (this.hand === 'left') {
  70599. return this.onMainButtonStateChangedObservable;
  70600. }
  70601. else {
  70602. throw new Error('No X button on right hand');
  70603. }
  70604. },
  70605. enumerable: true,
  70606. configurable: true
  70607. });
  70608. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70609. /**
  70610. * Fired when the Y button on this controller is modified
  70611. */
  70612. get: function () {
  70613. if (this.hand === 'left') {
  70614. return this.onSecondaryButtonStateChangedObservable;
  70615. }
  70616. else {
  70617. throw new Error('No Y button on right hand');
  70618. }
  70619. },
  70620. enumerable: true,
  70621. configurable: true
  70622. });
  70623. /**
  70624. * Called once for each button that changed state since the last frame
  70625. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70626. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70627. * 2) secondary trigger (same)
  70628. * 3) A (right) X (left), touch, pressed = value
  70629. * 4) B / Y
  70630. * 5) thumb rest
  70631. * @param buttonIdx Which button index changed
  70632. * @param state New state of the button
  70633. * @param changes Which properties on the state changed since last frame
  70634. */
  70635. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70636. var notifyObject = state; //{ state: state, changes: changes };
  70637. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70638. switch (buttonIdx) {
  70639. case 0:
  70640. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70641. return;
  70642. case 1: // index trigger
  70643. if (this._defaultModel) {
  70644. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70645. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70646. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70647. }
  70648. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70649. return;
  70650. case 2: // secondary trigger
  70651. if (this._defaultModel) {
  70652. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70653. }
  70654. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70655. return;
  70656. case 3:
  70657. if (this._defaultModel) {
  70658. if (notifyObject.pressed) {
  70659. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70660. }
  70661. else {
  70662. (this._defaultModel.getChildren()[1]).position.y = 0;
  70663. }
  70664. }
  70665. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70666. return;
  70667. case 4:
  70668. if (this._defaultModel) {
  70669. if (notifyObject.pressed) {
  70670. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70671. }
  70672. else {
  70673. (this._defaultModel.getChildren()[2]).position.y = 0;
  70674. }
  70675. }
  70676. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70677. return;
  70678. case 5:
  70679. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70680. return;
  70681. }
  70682. };
  70683. /**
  70684. * Base Url for the controller model.
  70685. */
  70686. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70687. /**
  70688. * File name for the left controller model.
  70689. */
  70690. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70691. /**
  70692. * File name for the right controller model.
  70693. */
  70694. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70695. return OculusTouchController;
  70696. }(BABYLON.WebVRController));
  70697. BABYLON.OculusTouchController = OculusTouchController;
  70698. })(BABYLON || (BABYLON = {}));
  70699. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70700. var BABYLON;
  70701. (function (BABYLON) {
  70702. /**
  70703. * Vive Controller
  70704. */
  70705. var ViveController = /** @class */ (function (_super) {
  70706. __extends(ViveController, _super);
  70707. /**
  70708. * Creates a new ViveController from a gamepad
  70709. * @param vrGamepad the gamepad that the controller should be created from
  70710. */
  70711. function ViveController(vrGamepad) {
  70712. var _this = _super.call(this, vrGamepad) || this;
  70713. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70714. _this._invertLeftStickY = true;
  70715. return _this;
  70716. }
  70717. /**
  70718. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70719. * @param scene scene in which to add meshes
  70720. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70721. */
  70722. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70723. var _this = this;
  70724. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70725. /*
  70726. Parent Mesh name: ViveWand
  70727. - body
  70728. - r_gripper
  70729. - l_gripper
  70730. - menu_button
  70731. - system_button
  70732. - trackpad
  70733. - trigger
  70734. - LED
  70735. */
  70736. _this._defaultModel = newMeshes[1];
  70737. _this.attachToMesh(_this._defaultModel);
  70738. if (meshLoaded) {
  70739. meshLoaded(_this._defaultModel);
  70740. }
  70741. });
  70742. };
  70743. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70744. /**
  70745. * Fired when the left button on this controller is modified
  70746. */
  70747. get: function () {
  70748. return this.onMainButtonStateChangedObservable;
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70754. /**
  70755. * Fired when the right button on this controller is modified
  70756. */
  70757. get: function () {
  70758. return this.onMainButtonStateChangedObservable;
  70759. },
  70760. enumerable: true,
  70761. configurable: true
  70762. });
  70763. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70764. /**
  70765. * Fired when the menu button on this controller is modified
  70766. */
  70767. get: function () {
  70768. return this.onSecondaryButtonStateChangedObservable;
  70769. },
  70770. enumerable: true,
  70771. configurable: true
  70772. });
  70773. /**
  70774. * Called once for each button that changed state since the last frame
  70775. * Vive mapping:
  70776. * 0: touchpad
  70777. * 1: trigger
  70778. * 2: left AND right buttons
  70779. * 3: menu button
  70780. * @param buttonIdx Which button index changed
  70781. * @param state New state of the button
  70782. * @param changes Which properties on the state changed since last frame
  70783. */
  70784. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70785. var notifyObject = state; //{ state: state, changes: changes };
  70786. switch (buttonIdx) {
  70787. case 0:
  70788. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70789. return;
  70790. case 1: // index trigger
  70791. if (this._defaultModel) {
  70792. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70793. }
  70794. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70795. return;
  70796. case 2: // left AND right button
  70797. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70798. return;
  70799. case 3:
  70800. if (this._defaultModel) {
  70801. if (notifyObject.pressed) {
  70802. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70803. }
  70804. else {
  70805. (this._defaultModel.getChildren()[2]).position.y = 0;
  70806. }
  70807. }
  70808. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70809. return;
  70810. }
  70811. };
  70812. /**
  70813. * Base Url for the controller model.
  70814. */
  70815. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70816. /**
  70817. * File name for the controller model.
  70818. */
  70819. ViveController.MODEL_FILENAME = 'wand.babylon';
  70820. return ViveController;
  70821. }(BABYLON.WebVRController));
  70822. BABYLON.ViveController = ViveController;
  70823. })(BABYLON || (BABYLON = {}));
  70824. //# sourceMappingURL=babylon.viveController.js.map
  70825. var BABYLON;
  70826. (function (BABYLON) {
  70827. /**
  70828. * Generic Controller
  70829. */
  70830. var GenericController = /** @class */ (function (_super) {
  70831. __extends(GenericController, _super);
  70832. /**
  70833. * Creates a new GenericController from a gamepad
  70834. * @param vrGamepad the gamepad that the controller should be created from
  70835. */
  70836. function GenericController(vrGamepad) {
  70837. return _super.call(this, vrGamepad) || this;
  70838. }
  70839. /**
  70840. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70841. * @param scene scene in which to add meshes
  70842. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70843. */
  70844. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70845. var _this = this;
  70846. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70847. _this._defaultModel = newMeshes[1];
  70848. _this.attachToMesh(_this._defaultModel);
  70849. if (meshLoaded) {
  70850. meshLoaded(_this._defaultModel);
  70851. }
  70852. });
  70853. };
  70854. /**
  70855. * Called once for each button that changed state since the last frame
  70856. * @param buttonIdx Which button index changed
  70857. * @param state New state of the button
  70858. * @param changes Which properties on the state changed since last frame
  70859. */
  70860. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70861. console.log("Button id: " + buttonIdx + "state: ");
  70862. console.dir(state);
  70863. };
  70864. /**
  70865. * Base Url for the controller model.
  70866. */
  70867. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70868. /**
  70869. * File name for the controller model.
  70870. */
  70871. GenericController.MODEL_FILENAME = 'generic.babylon';
  70872. return GenericController;
  70873. }(BABYLON.WebVRController));
  70874. BABYLON.GenericController = GenericController;
  70875. })(BABYLON || (BABYLON = {}));
  70876. //# sourceMappingURL=babylon.genericController.js.map
  70877. var BABYLON;
  70878. (function (BABYLON) {
  70879. /**
  70880. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70881. */
  70882. var LoadedMeshInfo = /** @class */ (function () {
  70883. function LoadedMeshInfo() {
  70884. /**
  70885. * Map of the button meshes contained in the controller
  70886. */
  70887. this.buttonMeshes = {};
  70888. /**
  70889. * Map of the axis meshes contained in the controller
  70890. */
  70891. this.axisMeshes = {};
  70892. }
  70893. return LoadedMeshInfo;
  70894. }());
  70895. /**
  70896. * Defines the WindowsMotionController object that the state of the windows motion controller
  70897. */
  70898. var WindowsMotionController = /** @class */ (function (_super) {
  70899. __extends(WindowsMotionController, _super);
  70900. /**
  70901. * Creates a new WindowsMotionController from a gamepad
  70902. * @param vrGamepad the gamepad that the controller should be created from
  70903. */
  70904. function WindowsMotionController(vrGamepad) {
  70905. var _this = _super.call(this, vrGamepad) || this;
  70906. _this._mapping = {
  70907. // Semantic button names
  70908. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70909. // A mapping of the button name to glTF model node name
  70910. // that should be transformed by button value.
  70911. buttonMeshNames: {
  70912. 'trigger': 'SELECT',
  70913. 'menu': 'MENU',
  70914. 'grip': 'GRASP',
  70915. 'thumbstick': 'THUMBSTICK_PRESS',
  70916. 'trackpad': 'TOUCHPAD_PRESS'
  70917. },
  70918. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70919. buttonObservableNames: {
  70920. 'trigger': 'onTriggerStateChangedObservable',
  70921. 'menu': 'onSecondaryButtonStateChangedObservable',
  70922. 'grip': 'onMainButtonStateChangedObservable',
  70923. 'thumbstick': 'onPadStateChangedObservable',
  70924. 'trackpad': 'onTrackpadChangedObservable'
  70925. },
  70926. // A mapping of the axis name to glTF model node name
  70927. // that should be transformed by axis value.
  70928. // This array mirrors the browserGamepad.axes array, such that
  70929. // the mesh corresponding to axis 0 is in this array index 0.
  70930. axisMeshNames: [
  70931. 'THUMBSTICK_X',
  70932. 'THUMBSTICK_Y',
  70933. 'TOUCHPAD_TOUCH_X',
  70934. 'TOUCHPAD_TOUCH_Y'
  70935. ],
  70936. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70937. };
  70938. /**
  70939. * Fired when the trackpad on this controller is clicked
  70940. */
  70941. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70942. /**
  70943. * Fired when the trackpad on this controller is modified
  70944. */
  70945. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70946. /**
  70947. * The current x and y values of this controller's trackpad
  70948. */
  70949. _this.trackpad = { x: 0, y: 0 };
  70950. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70951. _this._loadedMeshInfo = null;
  70952. return _this;
  70953. }
  70954. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70955. /**
  70956. * Fired when the trigger on this controller is modified
  70957. */
  70958. get: function () {
  70959. return this.onTriggerStateChangedObservable;
  70960. },
  70961. enumerable: true,
  70962. configurable: true
  70963. });
  70964. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70965. /**
  70966. * Fired when the menu button on this controller is modified
  70967. */
  70968. get: function () {
  70969. return this.onSecondaryButtonStateChangedObservable;
  70970. },
  70971. enumerable: true,
  70972. configurable: true
  70973. });
  70974. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70975. /**
  70976. * Fired when the grip button on this controller is modified
  70977. */
  70978. get: function () {
  70979. return this.onMainButtonStateChangedObservable;
  70980. },
  70981. enumerable: true,
  70982. configurable: true
  70983. });
  70984. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70985. /**
  70986. * Fired when the thumbstick button on this controller is modified
  70987. */
  70988. get: function () {
  70989. return this.onPadStateChangedObservable;
  70990. },
  70991. enumerable: true,
  70992. configurable: true
  70993. });
  70994. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70995. /**
  70996. * Fired when the touchpad button on this controller is modified
  70997. */
  70998. get: function () {
  70999. return this.onTrackpadChangedObservable;
  71000. },
  71001. enumerable: true,
  71002. configurable: true
  71003. });
  71004. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71005. /**
  71006. * Fired when the touchpad values on this controller are modified
  71007. */
  71008. get: function () {
  71009. return this.onTrackpadValuesChangedObservable;
  71010. },
  71011. enumerable: true,
  71012. configurable: true
  71013. });
  71014. /**
  71015. * Called once per frame by the engine.
  71016. */
  71017. WindowsMotionController.prototype.update = function () {
  71018. _super.prototype.update.call(this);
  71019. if (this.browserGamepad.axes) {
  71020. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71021. this.trackpad.x = this.browserGamepad["axes"][2];
  71022. this.trackpad.y = this.browserGamepad["axes"][3];
  71023. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71024. }
  71025. // Only need to animate axes if there is a loaded mesh
  71026. if (this._loadedMeshInfo) {
  71027. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71028. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71029. }
  71030. }
  71031. }
  71032. };
  71033. /**
  71034. * Called once for each button that changed state since the last frame
  71035. * @param buttonIdx Which button index changed
  71036. * @param state New state of the button
  71037. * @param changes Which properties on the state changed since last frame
  71038. */
  71039. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71040. var buttonName = this._mapping.buttons[buttonIdx];
  71041. if (!buttonName) {
  71042. return;
  71043. }
  71044. // Only emit events for buttons that we know how to map from index to name
  71045. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71046. if (observable) {
  71047. observable.notifyObservers(state);
  71048. }
  71049. this._lerpButtonTransform(buttonName, state.value);
  71050. };
  71051. /**
  71052. * Moves the buttons on the controller mesh based on their current state
  71053. * @param buttonName the name of the button to move
  71054. * @param buttonValue the value of the button which determines the buttons new position
  71055. */
  71056. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71057. // If there is no loaded mesh, there is nothing to transform.
  71058. if (!this._loadedMeshInfo) {
  71059. return;
  71060. }
  71061. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71062. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71063. return;
  71064. }
  71065. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71066. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71067. };
  71068. /**
  71069. * Moves the axis on the controller mesh based on its current state
  71070. * @param axis the index of the axis
  71071. * @param axisValue the value of the axis which determines the meshes new position
  71072. * @ignore
  71073. */
  71074. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71075. if (!this._loadedMeshInfo) {
  71076. return;
  71077. }
  71078. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71079. if (!meshInfo) {
  71080. return;
  71081. }
  71082. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71083. return;
  71084. }
  71085. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71086. var lerpValue = axisValue * 0.5 + 0.5;
  71087. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71088. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71089. };
  71090. /**
  71091. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71092. * @param scene scene in which to add meshes
  71093. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71094. */
  71095. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71096. var _this = this;
  71097. if (forceDefault === void 0) { forceDefault = false; }
  71098. var path;
  71099. var filename;
  71100. // Checking if GLB loader is present
  71101. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71102. // Determine the device specific folder based on the ID suffix
  71103. var device = 'default';
  71104. if (this.id && !forceDefault) {
  71105. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71106. device = ((match && match[0]) || device);
  71107. }
  71108. // Hand
  71109. if (this.hand === 'left') {
  71110. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71111. }
  71112. else { // Right is the default if no hand is specified
  71113. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71114. }
  71115. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71116. }
  71117. else {
  71118. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71119. path = BABYLON.GenericController.MODEL_BASE_URL;
  71120. filename = BABYLON.GenericController.MODEL_FILENAME;
  71121. }
  71122. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71123. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71124. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71125. if (!_this._loadedMeshInfo) {
  71126. return;
  71127. }
  71128. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71129. _this.attachToMesh(_this._defaultModel);
  71130. if (meshLoaded) {
  71131. meshLoaded(_this._defaultModel);
  71132. }
  71133. }, null, function (scene, message) {
  71134. BABYLON.Tools.Log(message);
  71135. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71136. if (!forceDefault) {
  71137. _this.initControllerMesh(scene, meshLoaded, true);
  71138. }
  71139. });
  71140. };
  71141. /**
  71142. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71143. * can be transformed by button presses and axes values, based on this._mapping.
  71144. *
  71145. * @param scene scene in which the meshes exist
  71146. * @param meshes list of meshes that make up the controller model to process
  71147. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71148. */
  71149. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71150. var loadedMeshInfo = null;
  71151. // Create a new mesh to contain the glTF hierarchy
  71152. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71153. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71154. var childMesh = null;
  71155. for (var i = 0; i < meshes.length; i++) {
  71156. var mesh = meshes[i];
  71157. if (!mesh.parent) {
  71158. // Exclude controller meshes from picking results
  71159. mesh.isPickable = false;
  71160. // Handle root node, attach to the new parentMesh
  71161. childMesh = mesh;
  71162. break;
  71163. }
  71164. }
  71165. if (childMesh) {
  71166. childMesh.setParent(parentMesh);
  71167. // Create our mesh info. Note that this method will always return non-null.
  71168. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71169. }
  71170. else {
  71171. BABYLON.Tools.Warn('Could not find root node in model file.');
  71172. }
  71173. return loadedMeshInfo;
  71174. };
  71175. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71176. var loadedMeshInfo = new LoadedMeshInfo();
  71177. var i;
  71178. loadedMeshInfo.rootNode = rootNode;
  71179. // Reset the caches
  71180. loadedMeshInfo.buttonMeshes = {};
  71181. loadedMeshInfo.axisMeshes = {};
  71182. // Button Meshes
  71183. for (i = 0; i < this._mapping.buttons.length; i++) {
  71184. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71185. if (!buttonMeshName) {
  71186. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71187. continue;
  71188. }
  71189. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71190. if (!buttonMesh) {
  71191. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71192. continue;
  71193. }
  71194. var buttonMeshInfo = {
  71195. index: i,
  71196. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71197. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71198. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71199. };
  71200. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71201. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71202. }
  71203. else {
  71204. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71205. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71206. '(VALUE: ' + !!buttonMeshInfo.value +
  71207. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71208. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71209. ')');
  71210. }
  71211. }
  71212. // Axis Meshes
  71213. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71214. var axisMeshName = this._mapping.axisMeshNames[i];
  71215. if (!axisMeshName) {
  71216. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71217. continue;
  71218. }
  71219. var axisMesh = getChildByName(rootNode, axisMeshName);
  71220. if (!axisMesh) {
  71221. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71222. continue;
  71223. }
  71224. var axisMeshInfo = {
  71225. index: i,
  71226. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71227. min: getImmediateChildByName(axisMesh, 'MIN'),
  71228. max: getImmediateChildByName(axisMesh, 'MAX')
  71229. };
  71230. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71231. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71232. }
  71233. else {
  71234. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71235. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71236. '(VALUE: ' + !!axisMeshInfo.value +
  71237. ', MIN: ' + !!axisMeshInfo.min +
  71238. ', MAX:' + !!axisMeshInfo.max +
  71239. ')');
  71240. }
  71241. }
  71242. // Pointing Ray
  71243. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71244. if (!loadedMeshInfo.pointingPoseNode) {
  71245. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71246. }
  71247. return loadedMeshInfo;
  71248. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71249. function getChildByName(node, name) {
  71250. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71251. }
  71252. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71253. function getImmediateChildByName(node, name) {
  71254. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71255. }
  71256. };
  71257. /**
  71258. * Gets the ray of the controller in the direction the controller is pointing
  71259. * @param length the length the resulting ray should be
  71260. * @returns a ray in the direction the controller is pointing
  71261. */
  71262. WindowsMotionController.prototype.getForwardRay = function (length) {
  71263. if (length === void 0) { length = 100; }
  71264. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71265. return _super.prototype.getForwardRay.call(this, length);
  71266. }
  71267. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71268. var origin = m.getTranslation();
  71269. var forward = new BABYLON.Vector3(0, 0, -1);
  71270. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71271. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71272. return new BABYLON.Ray(origin, direction, length);
  71273. };
  71274. /**
  71275. * Disposes of the controller
  71276. */
  71277. WindowsMotionController.prototype.dispose = function () {
  71278. _super.prototype.dispose.call(this);
  71279. this.onTrackpadChangedObservable.clear();
  71280. };
  71281. /**
  71282. * The base url used to load the left and right controller models
  71283. */
  71284. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71285. /**
  71286. * The name of the left controller model file
  71287. */
  71288. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71289. /**
  71290. * The name of the right controller model file
  71291. */
  71292. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71293. /**
  71294. * The controller name prefix for this controller type
  71295. */
  71296. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71297. /**
  71298. * The controller id pattern for this controller type
  71299. */
  71300. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71301. return WindowsMotionController;
  71302. }(BABYLON.WebVRController));
  71303. BABYLON.WindowsMotionController = WindowsMotionController;
  71304. })(BABYLON || (BABYLON = {}));
  71305. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71306. var BABYLON;
  71307. (function (BABYLON) {
  71308. /**
  71309. * Gear VR Controller
  71310. */
  71311. var GearVRController = /** @class */ (function (_super) {
  71312. __extends(GearVRController, _super);
  71313. /**
  71314. * Creates a new GearVRController from a gamepad
  71315. * @param vrGamepad the gamepad that the controller should be created from
  71316. */
  71317. function GearVRController(vrGamepad) {
  71318. var _this = _super.call(this, vrGamepad) || this;
  71319. _this._buttonIndexToObservableNameMap = [
  71320. 'onTrackpadChangedObservable',
  71321. 'onTriggerStateChangedObservable' // Trigger
  71322. ];
  71323. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71324. return _this;
  71325. }
  71326. /**
  71327. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71328. * @param scene scene in which to add meshes
  71329. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71330. */
  71331. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71332. var _this = this;
  71333. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71334. _this._defaultModel = newMeshes[1];
  71335. _this.attachToMesh(_this._defaultModel);
  71336. if (meshLoaded) {
  71337. meshLoaded(_this._defaultModel);
  71338. }
  71339. });
  71340. };
  71341. /**
  71342. * Called once for each button that changed state since the last frame
  71343. * @param buttonIdx Which button index changed
  71344. * @param state New state of the button
  71345. * @param changes Which properties on the state changed since last frame
  71346. */
  71347. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71348. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71349. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71350. // Only emit events for buttons that we know how to map from index to observable
  71351. var observable = this[observableName];
  71352. if (observable) {
  71353. observable.notifyObservers(state);
  71354. }
  71355. }
  71356. };
  71357. /**
  71358. * Base Url for the controller model.
  71359. */
  71360. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71361. /**
  71362. * File name for the controller model.
  71363. */
  71364. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71365. /**
  71366. * Gamepad Id prefix used to identify this controller.
  71367. */
  71368. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71369. return GearVRController;
  71370. }(BABYLON.WebVRController));
  71371. BABYLON.GearVRController = GearVRController;
  71372. })(BABYLON || (BABYLON = {}));
  71373. //# sourceMappingURL=babylon.gearVRController.js.map
  71374. var BABYLON;
  71375. (function (BABYLON) {
  71376. /**
  71377. * Google Daydream controller
  71378. */
  71379. var DaydreamController = /** @class */ (function (_super) {
  71380. __extends(DaydreamController, _super);
  71381. /**
  71382. * Creates a new DaydreamController from a gamepad
  71383. * @param vrGamepad the gamepad that the controller should be created from
  71384. */
  71385. function DaydreamController(vrGamepad) {
  71386. var _this = _super.call(this, vrGamepad) || this;
  71387. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71388. return _this;
  71389. }
  71390. /**
  71391. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71392. * @param scene scene in which to add meshes
  71393. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71394. */
  71395. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71396. var _this = this;
  71397. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71398. _this._defaultModel = newMeshes[1];
  71399. _this.attachToMesh(_this._defaultModel);
  71400. if (meshLoaded) {
  71401. meshLoaded(_this._defaultModel);
  71402. }
  71403. });
  71404. };
  71405. /**
  71406. * Called once for each button that changed state since the last frame
  71407. * @param buttonIdx Which button index changed
  71408. * @param state New state of the button
  71409. * @param changes Which properties on the state changed since last frame
  71410. */
  71411. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71412. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71413. if (buttonIdx === 0) {
  71414. var observable = this.onTriggerStateChangedObservable;
  71415. if (observable) {
  71416. observable.notifyObservers(state);
  71417. }
  71418. }
  71419. else {
  71420. // If the app or home buttons are ever made available
  71421. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71422. }
  71423. };
  71424. /**
  71425. * Base Url for the controller model.
  71426. */
  71427. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71428. /**
  71429. * File name for the controller model.
  71430. */
  71431. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71432. /**
  71433. * Gamepad Id prefix used to identify Daydream Controller.
  71434. */
  71435. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71436. return DaydreamController;
  71437. }(BABYLON.WebVRController));
  71438. BABYLON.DaydreamController = DaydreamController;
  71439. })(BABYLON || (BABYLON = {}));
  71440. //# sourceMappingURL=babylon.daydreamController.js.map
  71441. var BABYLON;
  71442. (function (BABYLON) {
  71443. var FollowCamera = /** @class */ (function (_super) {
  71444. __extends(FollowCamera, _super);
  71445. function FollowCamera(name, position, scene, lockedTarget) {
  71446. if (lockedTarget === void 0) { lockedTarget = null; }
  71447. var _this = _super.call(this, name, position, scene) || this;
  71448. _this.radius = 12;
  71449. _this.rotationOffset = 0;
  71450. _this.heightOffset = 4;
  71451. _this.cameraAcceleration = 0.05;
  71452. _this.maxCameraSpeed = 20;
  71453. _this.lockedTarget = lockedTarget;
  71454. return _this;
  71455. }
  71456. FollowCamera.prototype.getRadians = function (degrees) {
  71457. return degrees * Math.PI / 180;
  71458. };
  71459. FollowCamera.prototype.follow = function (cameraTarget) {
  71460. if (!cameraTarget)
  71461. return;
  71462. var yRotation;
  71463. if (cameraTarget.rotationQuaternion) {
  71464. var rotMatrix = new BABYLON.Matrix();
  71465. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71466. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71467. }
  71468. else {
  71469. yRotation = cameraTarget.rotation.y;
  71470. }
  71471. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71472. var targetPosition = cameraTarget.getAbsolutePosition();
  71473. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71474. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71475. var dx = targetX - this.position.x;
  71476. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71477. var dz = (targetZ) - this.position.z;
  71478. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71479. var vy = dy * this.cameraAcceleration;
  71480. var vz = dz * this.cameraAcceleration * 2;
  71481. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71482. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71483. }
  71484. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71485. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71486. }
  71487. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71488. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71489. }
  71490. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71491. this.setTarget(targetPosition);
  71492. };
  71493. FollowCamera.prototype._checkInputs = function () {
  71494. _super.prototype._checkInputs.call(this);
  71495. if (this.lockedTarget) {
  71496. this.follow(this.lockedTarget);
  71497. }
  71498. };
  71499. FollowCamera.prototype.getClassName = function () {
  71500. return "FollowCamera";
  71501. };
  71502. __decorate([
  71503. BABYLON.serialize()
  71504. ], FollowCamera.prototype, "radius", void 0);
  71505. __decorate([
  71506. BABYLON.serialize()
  71507. ], FollowCamera.prototype, "rotationOffset", void 0);
  71508. __decorate([
  71509. BABYLON.serialize()
  71510. ], FollowCamera.prototype, "heightOffset", void 0);
  71511. __decorate([
  71512. BABYLON.serialize()
  71513. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71514. __decorate([
  71515. BABYLON.serialize()
  71516. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71517. __decorate([
  71518. BABYLON.serializeAsMeshReference("lockedTargetId")
  71519. ], FollowCamera.prototype, "lockedTarget", void 0);
  71520. return FollowCamera;
  71521. }(BABYLON.TargetCamera));
  71522. BABYLON.FollowCamera = FollowCamera;
  71523. var ArcFollowCamera = /** @class */ (function (_super) {
  71524. __extends(ArcFollowCamera, _super);
  71525. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71526. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71527. _this.alpha = alpha;
  71528. _this.beta = beta;
  71529. _this.radius = radius;
  71530. _this.target = target;
  71531. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71532. _this.follow();
  71533. return _this;
  71534. }
  71535. ArcFollowCamera.prototype.follow = function () {
  71536. if (!this.target) {
  71537. return;
  71538. }
  71539. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71540. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71541. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71542. var targetPosition = this.target.getAbsolutePosition();
  71543. this.position = targetPosition.add(this._cartesianCoordinates);
  71544. this.setTarget(targetPosition);
  71545. };
  71546. ArcFollowCamera.prototype._checkInputs = function () {
  71547. _super.prototype._checkInputs.call(this);
  71548. this.follow();
  71549. };
  71550. ArcFollowCamera.prototype.getClassName = function () {
  71551. return "ArcFollowCamera";
  71552. };
  71553. return ArcFollowCamera;
  71554. }(BABYLON.TargetCamera));
  71555. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71556. })(BABYLON || (BABYLON = {}));
  71557. //# sourceMappingURL=babylon.followCamera.js.map
  71558. var BABYLON;
  71559. (function (BABYLON) {
  71560. // We're mainly based on the logic defined into the FreeCamera code
  71561. var UniversalCamera = /** @class */ (function (_super) {
  71562. __extends(UniversalCamera, _super);
  71563. //-- end properties for backward compatibility for inputs
  71564. function UniversalCamera(name, position, scene) {
  71565. var _this = _super.call(this, name, position, scene) || this;
  71566. _this.inputs.addGamepad();
  71567. return _this;
  71568. }
  71569. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71570. //-- Begin properties for backward compatibility for inputs
  71571. get: function () {
  71572. var gamepad = this.inputs.attached["gamepad"];
  71573. if (gamepad)
  71574. return gamepad.gamepadAngularSensibility;
  71575. return 0;
  71576. },
  71577. set: function (value) {
  71578. var gamepad = this.inputs.attached["gamepad"];
  71579. if (gamepad)
  71580. gamepad.gamepadAngularSensibility = value;
  71581. },
  71582. enumerable: true,
  71583. configurable: true
  71584. });
  71585. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71586. get: function () {
  71587. var gamepad = this.inputs.attached["gamepad"];
  71588. if (gamepad)
  71589. return gamepad.gamepadMoveSensibility;
  71590. return 0;
  71591. },
  71592. set: function (value) {
  71593. var gamepad = this.inputs.attached["gamepad"];
  71594. if (gamepad)
  71595. gamepad.gamepadMoveSensibility = value;
  71596. },
  71597. enumerable: true,
  71598. configurable: true
  71599. });
  71600. UniversalCamera.prototype.getClassName = function () {
  71601. return "UniversalCamera";
  71602. };
  71603. return UniversalCamera;
  71604. }(BABYLON.TouchCamera));
  71605. BABYLON.UniversalCamera = UniversalCamera;
  71606. })(BABYLON || (BABYLON = {}));
  71607. //# sourceMappingURL=babylon.universalCamera.js.map
  71608. var BABYLON;
  71609. (function (BABYLON) {
  71610. // We're mainly based on the logic defined into the FreeCamera code
  71611. var GamepadCamera = /** @class */ (function (_super) {
  71612. __extends(GamepadCamera, _super);
  71613. //-- end properties for backward compatibility for inputs
  71614. function GamepadCamera(name, position, scene) {
  71615. return _super.call(this, name, position, scene) || this;
  71616. }
  71617. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71618. //-- Begin properties for backward compatibility for inputs
  71619. get: function () {
  71620. var gamepad = this.inputs.attached["gamepad"];
  71621. if (gamepad)
  71622. return gamepad.gamepadAngularSensibility;
  71623. return 0;
  71624. },
  71625. set: function (value) {
  71626. var gamepad = this.inputs.attached["gamepad"];
  71627. if (gamepad)
  71628. gamepad.gamepadAngularSensibility = value;
  71629. },
  71630. enumerable: true,
  71631. configurable: true
  71632. });
  71633. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71634. get: function () {
  71635. var gamepad = this.inputs.attached["gamepad"];
  71636. if (gamepad)
  71637. return gamepad.gamepadMoveSensibility;
  71638. return 0;
  71639. },
  71640. set: function (value) {
  71641. var gamepad = this.inputs.attached["gamepad"];
  71642. if (gamepad)
  71643. gamepad.gamepadMoveSensibility = value;
  71644. },
  71645. enumerable: true,
  71646. configurable: true
  71647. });
  71648. GamepadCamera.prototype.getClassName = function () {
  71649. return "GamepadCamera";
  71650. };
  71651. return GamepadCamera;
  71652. }(BABYLON.UniversalCamera));
  71653. BABYLON.GamepadCamera = GamepadCamera;
  71654. })(BABYLON || (BABYLON = {}));
  71655. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71656. var BABYLON;
  71657. (function (BABYLON) {
  71658. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71659. function PostProcessRenderPipelineManager() {
  71660. this._renderPipelines = {};
  71661. }
  71662. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71663. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71664. };
  71665. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71666. if (unique === void 0) { unique = false; }
  71667. var renderPipeline = this._renderPipelines[renderPipelineName];
  71668. if (!renderPipeline) {
  71669. return;
  71670. }
  71671. renderPipeline._attachCameras(cameras, unique);
  71672. };
  71673. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71674. var renderPipeline = this._renderPipelines[renderPipelineName];
  71675. if (!renderPipeline) {
  71676. return;
  71677. }
  71678. renderPipeline._detachCameras(cameras);
  71679. };
  71680. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71681. var renderPipeline = this._renderPipelines[renderPipelineName];
  71682. if (!renderPipeline) {
  71683. return;
  71684. }
  71685. renderPipeline._enableEffect(renderEffectName, cameras);
  71686. };
  71687. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71688. var renderPipeline = this._renderPipelines[renderPipelineName];
  71689. if (!renderPipeline) {
  71690. return;
  71691. }
  71692. renderPipeline._disableEffect(renderEffectName, cameras);
  71693. };
  71694. PostProcessRenderPipelineManager.prototype.update = function () {
  71695. for (var renderPipelineName in this._renderPipelines) {
  71696. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71697. var pipeline = this._renderPipelines[renderPipelineName];
  71698. if (!pipeline.isSupported) {
  71699. pipeline.dispose();
  71700. delete this._renderPipelines[renderPipelineName];
  71701. }
  71702. else {
  71703. pipeline._update();
  71704. }
  71705. }
  71706. }
  71707. };
  71708. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71709. for (var renderPipelineName in this._renderPipelines) {
  71710. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71711. var pipeline = this._renderPipelines[renderPipelineName];
  71712. pipeline._rebuild();
  71713. }
  71714. }
  71715. };
  71716. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71717. for (var renderPipelineName in this._renderPipelines) {
  71718. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71719. var pipeline = this._renderPipelines[renderPipelineName];
  71720. pipeline.dispose();
  71721. }
  71722. }
  71723. };
  71724. return PostProcessRenderPipelineManager;
  71725. }());
  71726. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71727. })(BABYLON || (BABYLON = {}));
  71728. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71729. var BABYLON;
  71730. (function (BABYLON) {
  71731. /**
  71732. * This represents a set of one or more post processes in Babylon.
  71733. * A post process can be used to apply a shader to a texture after it is rendered.
  71734. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71735. */
  71736. var PostProcessRenderEffect = /** @class */ (function () {
  71737. /**
  71738. * Instantiates a post process render effect.
  71739. * A post process can be used to apply a shader to a texture after it is rendered.
  71740. * @param engine The engine the effect is tied to
  71741. * @param name The name of the effect
  71742. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71743. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71744. */
  71745. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71746. this._name = name;
  71747. this._singleInstance = singleInstance || true;
  71748. this._getPostProcesses = getPostProcesses;
  71749. this._cameras = {};
  71750. this._indicesForCamera = {};
  71751. this._postProcesses = {};
  71752. }
  71753. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71754. /**
  71755. * Checks if all the post processes in the effect are supported.
  71756. */
  71757. get: function () {
  71758. for (var index in this._postProcesses) {
  71759. if (this._postProcesses.hasOwnProperty(index)) {
  71760. var pps = this._postProcesses[index];
  71761. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71762. if (!pps[ppIndex].isSupported) {
  71763. return false;
  71764. }
  71765. }
  71766. }
  71767. }
  71768. return true;
  71769. },
  71770. enumerable: true,
  71771. configurable: true
  71772. });
  71773. /**
  71774. * Updates the current state of the effect
  71775. */
  71776. PostProcessRenderEffect.prototype._update = function () {
  71777. };
  71778. /**
  71779. * Attaches the effect on cameras
  71780. * @param cameras The camera to attach to.
  71781. */
  71782. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71783. var _this = this;
  71784. var cameraKey;
  71785. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71786. if (!cams) {
  71787. return;
  71788. }
  71789. for (var i = 0; i < cams.length; i++) {
  71790. var camera = cams[i];
  71791. var cameraName = camera.name;
  71792. if (this._singleInstance) {
  71793. cameraKey = 0;
  71794. }
  71795. else {
  71796. cameraKey = cameraName;
  71797. }
  71798. if (!this._postProcesses[cameraKey]) {
  71799. var postProcess = this._getPostProcesses();
  71800. if (postProcess) {
  71801. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71802. }
  71803. }
  71804. if (!this._indicesForCamera[cameraName]) {
  71805. this._indicesForCamera[cameraName] = [];
  71806. }
  71807. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71808. var index = camera.attachPostProcess(postProcess);
  71809. _this._indicesForCamera[cameraName].push(index);
  71810. });
  71811. if (!this._cameras[cameraName]) {
  71812. this._cameras[cameraName] = camera;
  71813. }
  71814. }
  71815. };
  71816. /**
  71817. * Detatches the effect on cameras
  71818. * @param cameras The camera to detatch from.
  71819. */
  71820. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71821. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71822. if (!cams) {
  71823. return;
  71824. }
  71825. for (var i = 0; i < cams.length; i++) {
  71826. var camera = cams[i];
  71827. var cameraName = camera.name;
  71828. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71829. camera.detachPostProcess(postProcess);
  71830. });
  71831. if (this._cameras[cameraName]) {
  71832. //this._indicesForCamera.splice(index, 1);
  71833. this._cameras[cameraName] = null;
  71834. }
  71835. }
  71836. };
  71837. /**
  71838. * Enables the effect on given cameras
  71839. * @param cameras The camera to enable.
  71840. */
  71841. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71842. var _this = this;
  71843. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71844. if (!cams) {
  71845. return;
  71846. }
  71847. for (var i = 0; i < cams.length; i++) {
  71848. var camera = cams[i];
  71849. var cameraName = camera.name;
  71850. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71851. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71852. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71853. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71854. });
  71855. }
  71856. }
  71857. }
  71858. };
  71859. /**
  71860. * Disables the effect on the given cameras
  71861. * @param cameras The camera to disable.
  71862. */
  71863. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71864. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71865. if (!cams) {
  71866. return;
  71867. }
  71868. for (var i = 0; i < cams.length; i++) {
  71869. var camera = cams[i];
  71870. var cameraName = camera.name;
  71871. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71872. camera.detachPostProcess(postProcess);
  71873. });
  71874. }
  71875. };
  71876. /**
  71877. * Gets a list of the post processes contained in the effect.
  71878. * @param camera The camera to get the post processes on.
  71879. * @returns The list of the post processes in the effect.
  71880. */
  71881. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71882. if (this._singleInstance) {
  71883. return this._postProcesses[0];
  71884. }
  71885. else {
  71886. if (!camera) {
  71887. return null;
  71888. }
  71889. return this._postProcesses[camera.name];
  71890. }
  71891. };
  71892. return PostProcessRenderEffect;
  71893. }());
  71894. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71895. })(BABYLON || (BABYLON = {}));
  71896. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71897. var BABYLON;
  71898. (function (BABYLON) {
  71899. var PostProcessRenderPipeline = /** @class */ (function () {
  71900. function PostProcessRenderPipeline(engine, name) {
  71901. this.engine = engine;
  71902. this._name = name;
  71903. this._renderEffects = {};
  71904. this._renderEffectsForIsolatedPass = new Array();
  71905. this._cameras = [];
  71906. }
  71907. PostProcessRenderPipeline.prototype.getClassName = function () {
  71908. return "PostProcessRenderPipeline";
  71909. };
  71910. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71911. get: function () {
  71912. for (var renderEffectName in this._renderEffects) {
  71913. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71914. if (!this._renderEffects[renderEffectName].isSupported) {
  71915. return false;
  71916. }
  71917. }
  71918. }
  71919. return true;
  71920. },
  71921. enumerable: true,
  71922. configurable: true
  71923. });
  71924. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71925. this._renderEffects[renderEffect._name] = renderEffect;
  71926. };
  71927. // private
  71928. PostProcessRenderPipeline.prototype._rebuild = function () {
  71929. };
  71930. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71931. var renderEffects = this._renderEffects[renderEffectName];
  71932. if (!renderEffects) {
  71933. return;
  71934. }
  71935. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71936. };
  71937. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71938. var renderEffects = this._renderEffects[renderEffectName];
  71939. if (!renderEffects) {
  71940. return;
  71941. }
  71942. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71943. };
  71944. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71945. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71946. if (!cams) {
  71947. return;
  71948. }
  71949. var indicesToDelete = [];
  71950. var i;
  71951. for (i = 0; i < cams.length; i++) {
  71952. var camera = cams[i];
  71953. var cameraName = camera.name;
  71954. if (this._cameras.indexOf(camera) === -1) {
  71955. this._cameras[cameraName] = camera;
  71956. }
  71957. else if (unique) {
  71958. indicesToDelete.push(i);
  71959. }
  71960. }
  71961. for (i = 0; i < indicesToDelete.length; i++) {
  71962. cameras.splice(indicesToDelete[i], 1);
  71963. }
  71964. for (var renderEffectName in this._renderEffects) {
  71965. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71966. this._renderEffects[renderEffectName]._attachCameras(cams);
  71967. }
  71968. }
  71969. };
  71970. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71971. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71972. if (!cams) {
  71973. return;
  71974. }
  71975. for (var renderEffectName in this._renderEffects) {
  71976. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71977. this._renderEffects[renderEffectName]._detachCameras(cams);
  71978. }
  71979. }
  71980. for (var i = 0; i < cams.length; i++) {
  71981. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71982. }
  71983. };
  71984. PostProcessRenderPipeline.prototype._update = function () {
  71985. for (var renderEffectName in this._renderEffects) {
  71986. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71987. this._renderEffects[renderEffectName]._update();
  71988. }
  71989. }
  71990. for (var i = 0; i < this._cameras.length; i++) {
  71991. var cameraName = this._cameras[i].name;
  71992. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71993. this._renderEffectsForIsolatedPass[cameraName]._update();
  71994. }
  71995. }
  71996. };
  71997. PostProcessRenderPipeline.prototype._reset = function () {
  71998. this._renderEffects = {};
  71999. this._renderEffectsForIsolatedPass = new Array();
  72000. };
  72001. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72002. // 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)
  72003. var effectKeys = Object.keys(this._renderEffects);
  72004. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72005. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72006. if (postProcesses) {
  72007. postProcesses[0].samples = sampleCount;
  72008. return true;
  72009. }
  72010. }
  72011. return false;
  72012. };
  72013. PostProcessRenderPipeline.prototype.dispose = function () {
  72014. // Must be implemented by children
  72015. };
  72016. __decorate([
  72017. BABYLON.serialize()
  72018. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72019. return PostProcessRenderPipeline;
  72020. }());
  72021. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72022. })(BABYLON || (BABYLON = {}));
  72023. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72024. var BABYLON;
  72025. (function (BABYLON) {
  72026. /**
  72027. * This represents a depth renderer in Babylon.
  72028. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72029. */
  72030. var DepthRenderer = /** @class */ (function () {
  72031. /**
  72032. * Instantiates a depth renderer
  72033. * @param scene The scene the renderer belongs to
  72034. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72035. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72036. */
  72037. function DepthRenderer(scene, type, camera) {
  72038. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72039. if (camera === void 0) { camera = null; }
  72040. var _this = this;
  72041. this._scene = scene;
  72042. this._camera = camera;
  72043. var engine = scene.getEngine();
  72044. // Render target
  72045. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72046. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72047. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72048. this._depthMap.refreshRate = 1;
  72049. this._depthMap.renderParticles = false;
  72050. this._depthMap.renderList = null;
  72051. // Camera to get depth map from to support multiple concurrent cameras
  72052. this._depthMap.activeCamera = this._camera;
  72053. this._depthMap.ignoreCameraViewport = true;
  72054. this._depthMap.useCameraPostProcesses = false;
  72055. // set default depth value to 1.0 (far away)
  72056. this._depthMap.onClearObservable.add(function (engine) {
  72057. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72058. });
  72059. // Custom render function
  72060. var renderSubMesh = function (subMesh) {
  72061. var mesh = subMesh.getRenderingMesh();
  72062. var scene = _this._scene;
  72063. var engine = scene.getEngine();
  72064. var material = subMesh.getMaterial();
  72065. if (!material) {
  72066. return;
  72067. }
  72068. // Culling and reverse (right handed system)
  72069. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72070. // Managing instances
  72071. var batch = mesh._getInstancesRenderList(subMesh._id);
  72072. if (batch.mustReturn) {
  72073. return;
  72074. }
  72075. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72076. var camera = _this._camera || scene.activeCamera;
  72077. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72078. engine.enableEffect(_this._effect);
  72079. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72080. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72081. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72082. // Alpha test
  72083. if (material && material.needAlphaTesting()) {
  72084. var alphaTexture = material.getAlphaTestTexture();
  72085. if (alphaTexture) {
  72086. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72087. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72088. }
  72089. }
  72090. // Bones
  72091. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72092. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72093. }
  72094. // Draw
  72095. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72096. }
  72097. };
  72098. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72099. var index;
  72100. if (depthOnlySubMeshes.length) {
  72101. engine.setColorWrite(false);
  72102. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72103. renderSubMesh(depthOnlySubMeshes.data[index]);
  72104. }
  72105. engine.setColorWrite(true);
  72106. }
  72107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72108. renderSubMesh(opaqueSubMeshes.data[index]);
  72109. }
  72110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72111. renderSubMesh(alphaTestSubMeshes.data[index]);
  72112. }
  72113. };
  72114. }
  72115. /**
  72116. * Creates the depth rendering effect and checks if the effect is ready.
  72117. * @param subMesh The submesh to be used to render the depth map of
  72118. * @param useInstances If multiple world instances should be used
  72119. * @returns if the depth renderer is ready to render the depth map
  72120. */
  72121. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72122. var material = subMesh.getMaterial();
  72123. if (material.disableDepthWrite) {
  72124. return false;
  72125. }
  72126. var defines = [];
  72127. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72128. var mesh = subMesh.getMesh();
  72129. // Alpha test
  72130. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72131. defines.push("#define ALPHATEST");
  72132. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72133. attribs.push(BABYLON.VertexBuffer.UVKind);
  72134. defines.push("#define UV1");
  72135. }
  72136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72137. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72138. defines.push("#define UV2");
  72139. }
  72140. }
  72141. // Bones
  72142. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72145. if (mesh.numBoneInfluencers > 4) {
  72146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72148. }
  72149. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72150. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72151. }
  72152. else {
  72153. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72154. }
  72155. // Instances
  72156. if (useInstances) {
  72157. defines.push("#define INSTANCES");
  72158. attribs.push("world0");
  72159. attribs.push("world1");
  72160. attribs.push("world2");
  72161. attribs.push("world3");
  72162. }
  72163. // Get correct effect
  72164. var join = defines.join("\n");
  72165. if (this._cachedDefines !== join) {
  72166. this._cachedDefines = join;
  72167. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72168. }
  72169. return this._effect.isReady();
  72170. };
  72171. /**
  72172. * Gets the texture which the depth map will be written to.
  72173. * @returns The depth map texture
  72174. */
  72175. DepthRenderer.prototype.getDepthMap = function () {
  72176. return this._depthMap;
  72177. };
  72178. /**
  72179. * Disposes of the depth renderer.
  72180. */
  72181. DepthRenderer.prototype.dispose = function () {
  72182. this._depthMap.dispose();
  72183. };
  72184. return DepthRenderer;
  72185. }());
  72186. BABYLON.DepthRenderer = DepthRenderer;
  72187. })(BABYLON || (BABYLON = {}));
  72188. //# sourceMappingURL=babylon.depthRenderer.js.map
  72189. var BABYLON;
  72190. (function (BABYLON) {
  72191. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72192. __extends(SSAORenderingPipeline, _super);
  72193. /**
  72194. * @constructor
  72195. * @param {string} name - The rendering pipeline name
  72196. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72197. * @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 }
  72198. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72199. */
  72200. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72201. var _this = _super.call(this, scene.getEngine(), name) || this;
  72202. // Members
  72203. /**
  72204. * The PassPostProcess id in the pipeline that contains the original scene color
  72205. */
  72206. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72207. /**
  72208. * The SSAO PostProcess id in the pipeline
  72209. */
  72210. _this.SSAORenderEffect = "SSAORenderEffect";
  72211. /**
  72212. * The horizontal blur PostProcess id in the pipeline
  72213. */
  72214. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72215. /**
  72216. * The vertical blur PostProcess id in the pipeline
  72217. */
  72218. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72219. /**
  72220. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72221. */
  72222. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72223. /**
  72224. * The output strength of the SSAO post-process. Default value is 1.0.
  72225. */
  72226. _this.totalStrength = 1.0;
  72227. /**
  72228. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72229. */
  72230. _this.radius = 0.0001;
  72231. /**
  72232. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72233. * Must not be equal to fallOff and superior to fallOff.
  72234. * Default value is 0.975
  72235. */
  72236. _this.area = 0.0075;
  72237. /**
  72238. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72239. * Must not be equal to area and inferior to area.
  72240. * Default value is 0.0
  72241. */
  72242. _this.fallOff = 0.000001;
  72243. /**
  72244. * The base color of the SSAO post-process
  72245. * The final result is "base + ssao" between [0, 1]
  72246. */
  72247. _this.base = 0.5;
  72248. _this._firstUpdate = true;
  72249. _this._scene = scene;
  72250. // Set up assets
  72251. _this._createRandomTexture();
  72252. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72253. var ssaoRatio = ratio.ssaoRatio || ratio;
  72254. var combineRatio = ratio.combineRatio || ratio;
  72255. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72256. _this._createSSAOPostProcess(ssaoRatio);
  72257. _this._createBlurPostProcess(ssaoRatio);
  72258. _this._createSSAOCombinePostProcess(combineRatio);
  72259. // Set up pipeline
  72260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72261. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72265. // Finish
  72266. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72267. if (cameras)
  72268. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72269. return _this;
  72270. }
  72271. // Public Methods
  72272. /**
  72273. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72274. */
  72275. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72276. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72277. for (var i = 0; i < this._scene.cameras.length; i++) {
  72278. var camera = this._scene.cameras[i];
  72279. this._originalColorPostProcess.dispose(camera);
  72280. this._ssaoPostProcess.dispose(camera);
  72281. this._blurHPostProcess.dispose(camera);
  72282. this._blurVPostProcess.dispose(camera);
  72283. this._ssaoCombinePostProcess.dispose(camera);
  72284. }
  72285. this._randomTexture.dispose();
  72286. if (disableDepthRender)
  72287. this._scene.disableDepthRenderer();
  72288. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72289. _super.prototype.dispose.call(this);
  72290. };
  72291. // Private Methods
  72292. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72293. var _this = this;
  72294. var size = 16;
  72295. 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);
  72296. 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);
  72297. this._blurHPostProcess.onActivateObservable.add(function () {
  72298. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72299. _this._blurHPostProcess.kernel = size * dw;
  72300. });
  72301. this._blurVPostProcess.onActivateObservable.add(function () {
  72302. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72303. _this._blurVPostProcess.kernel = size * dw;
  72304. });
  72305. };
  72306. SSAORenderingPipeline.prototype._rebuild = function () {
  72307. this._firstUpdate = true;
  72308. _super.prototype._rebuild.call(this);
  72309. };
  72310. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72311. var _this = this;
  72312. var numSamples = 16;
  72313. var sampleSphere = [
  72314. 0.5381, 0.1856, -0.4319,
  72315. 0.1379, 0.2486, 0.4430,
  72316. 0.3371, 0.5679, -0.0057,
  72317. -0.6999, -0.0451, -0.0019,
  72318. 0.0689, -0.1598, -0.8547,
  72319. 0.0560, 0.0069, -0.1843,
  72320. -0.0146, 0.1402, 0.0762,
  72321. 0.0100, -0.1924, -0.0344,
  72322. -0.3577, -0.5301, -0.4358,
  72323. -0.3169, 0.1063, 0.0158,
  72324. 0.0103, -0.5869, 0.0046,
  72325. -0.0897, -0.4940, 0.3287,
  72326. 0.7119, -0.0154, -0.0918,
  72327. -0.0533, 0.0596, -0.5411,
  72328. 0.0352, -0.0631, 0.5460,
  72329. -0.4776, 0.2847, -0.0271
  72330. ];
  72331. var samplesFactor = 1.0 / numSamples;
  72332. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72333. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72334. "area", "fallOff", "base", "range", "viewport"
  72335. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72336. this._ssaoPostProcess.onApply = function (effect) {
  72337. if (_this._firstUpdate) {
  72338. effect.setArray3("sampleSphere", sampleSphere);
  72339. effect.setFloat("samplesFactor", samplesFactor);
  72340. effect.setFloat("randTextureTiles", 4.0);
  72341. }
  72342. effect.setFloat("totalStrength", _this.totalStrength);
  72343. effect.setFloat("radius", _this.radius);
  72344. effect.setFloat("area", _this.area);
  72345. effect.setFloat("fallOff", _this.fallOff);
  72346. effect.setFloat("base", _this.base);
  72347. effect.setTexture("textureSampler", _this._depthTexture);
  72348. effect.setTexture("randomSampler", _this._randomTexture);
  72349. };
  72350. };
  72351. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72352. var _this = this;
  72353. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72354. this._ssaoCombinePostProcess.onApply = function (effect) {
  72355. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72356. };
  72357. };
  72358. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72359. var size = 512;
  72360. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72361. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72362. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72363. var context = this._randomTexture.getContext();
  72364. var rand = function (min, max) {
  72365. return Math.random() * (max - min) + min;
  72366. };
  72367. var randVector = BABYLON.Vector3.Zero();
  72368. for (var x = 0; x < size; x++) {
  72369. for (var y = 0; y < size; y++) {
  72370. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72371. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72372. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72373. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72374. context.fillRect(x, y, 1, 1);
  72375. }
  72376. }
  72377. this._randomTexture.update(false);
  72378. };
  72379. __decorate([
  72380. BABYLON.serialize()
  72381. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72382. __decorate([
  72383. BABYLON.serialize()
  72384. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72385. __decorate([
  72386. BABYLON.serialize()
  72387. ], SSAORenderingPipeline.prototype, "area", void 0);
  72388. __decorate([
  72389. BABYLON.serialize()
  72390. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72391. __decorate([
  72392. BABYLON.serialize()
  72393. ], SSAORenderingPipeline.prototype, "base", void 0);
  72394. return SSAORenderingPipeline;
  72395. }(BABYLON.PostProcessRenderPipeline));
  72396. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72397. })(BABYLON || (BABYLON = {}));
  72398. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72399. var BABYLON;
  72400. (function (BABYLON) {
  72401. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72402. __extends(SSAO2RenderingPipeline, _super);
  72403. /**
  72404. * @constructor
  72405. * @param {string} name - The rendering pipeline name
  72406. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72407. * @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 }
  72408. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72409. */
  72410. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72411. var _this = _super.call(this, scene.getEngine(), name) || this;
  72412. // Members
  72413. /**
  72414. * The PassPostProcess id in the pipeline that contains the original scene color
  72415. */
  72416. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72417. /**
  72418. * The SSAO PostProcess id in the pipeline
  72419. */
  72420. _this.SSAORenderEffect = "SSAORenderEffect";
  72421. /**
  72422. * The horizontal blur PostProcess id in the pipeline
  72423. */
  72424. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72425. /**
  72426. * The vertical blur PostProcess id in the pipeline
  72427. */
  72428. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72429. /**
  72430. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72431. */
  72432. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72433. /**
  72434. * The output strength of the SSAO post-process. Default value is 1.0.
  72435. */
  72436. _this.totalStrength = 1.0;
  72437. /**
  72438. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72439. */
  72440. _this.maxZ = 100.0;
  72441. /**
  72442. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72443. */
  72444. _this.minZAspect = 0.2;
  72445. /**
  72446. * Number of samples used for the SSAO calculations. Default value is 8
  72447. */
  72448. _this._samples = 8;
  72449. /**
  72450. * Are we using bilateral blur ?
  72451. */
  72452. _this._expensiveBlur = true;
  72453. /**
  72454. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72455. */
  72456. _this.radius = 2.0;
  72457. /**
  72458. * The base color of the SSAO post-process
  72459. * The final result is "base + ssao" between [0, 1]
  72460. */
  72461. _this.base = 0.1;
  72462. _this._firstUpdate = true;
  72463. _this._scene = scene;
  72464. if (!_this.isSupported) {
  72465. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72466. return _this;
  72467. }
  72468. var ssaoRatio = ratio.ssaoRatio || ratio;
  72469. var blurRatio = ratio.blurRatio || ratio;
  72470. // Set up assets
  72471. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72472. _this._createRandomTexture();
  72473. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72474. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72475. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72476. _this._createSSAOPostProcess(1.0);
  72477. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72478. _this._createSSAOCombinePostProcess(blurRatio);
  72479. // Set up pipeline
  72480. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72481. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72482. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72484. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72485. // Finish
  72486. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72487. if (cameras)
  72488. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72489. return _this;
  72490. }
  72491. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72492. get: function () {
  72493. return this._samples;
  72494. },
  72495. set: function (n) {
  72496. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72497. this._samples = n;
  72498. this._sampleSphere = this._generateHemisphere();
  72499. this._firstUpdate = true;
  72500. },
  72501. enumerable: true,
  72502. configurable: true
  72503. });
  72504. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72505. get: function () {
  72506. return this._expensiveBlur;
  72507. },
  72508. set: function (b) {
  72509. 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"]);
  72510. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72511. this._expensiveBlur = b;
  72512. this._firstUpdate = true;
  72513. },
  72514. enumerable: true,
  72515. configurable: true
  72516. });
  72517. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72518. /**
  72519. * Support test.
  72520. */
  72521. get: function () {
  72522. var engine = BABYLON.Engine.LastCreatedEngine;
  72523. if (!engine) {
  72524. return false;
  72525. }
  72526. return engine.getCaps().drawBuffersExtension;
  72527. },
  72528. enumerable: true,
  72529. configurable: true
  72530. });
  72531. // Public Methods
  72532. /**
  72533. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72534. */
  72535. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72536. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72537. for (var i = 0; i < this._scene.cameras.length; i++) {
  72538. var camera = this._scene.cameras[i];
  72539. this._originalColorPostProcess.dispose(camera);
  72540. this._ssaoPostProcess.dispose(camera);
  72541. this._blurHPostProcess.dispose(camera);
  72542. this._blurVPostProcess.dispose(camera);
  72543. this._ssaoCombinePostProcess.dispose(camera);
  72544. }
  72545. this._randomTexture.dispose();
  72546. if (disableGeometryBufferRenderer)
  72547. this._scene.disableGeometryBufferRenderer();
  72548. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72549. _super.prototype.dispose.call(this);
  72550. };
  72551. // Private Methods
  72552. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72553. var _this = this;
  72554. this._samplerOffsets = [];
  72555. var expensive = this.expensiveBlur;
  72556. for (var i = -8; i < 8; i++) {
  72557. this._samplerOffsets.push(i * 2 + 0.5);
  72558. }
  72559. 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");
  72560. this._blurHPostProcess.onApply = function (effect) {
  72561. if (!_this._scene.activeCamera) {
  72562. return;
  72563. }
  72564. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72565. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72566. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72567. effect.setFloat("radius", _this.radius);
  72568. effect.setTexture("depthSampler", _this._depthTexture);
  72569. if (_this._firstUpdate) {
  72570. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72571. }
  72572. };
  72573. 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");
  72574. this._blurVPostProcess.onApply = function (effect) {
  72575. if (!_this._scene.activeCamera) {
  72576. return;
  72577. }
  72578. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72579. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72580. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72581. effect.setFloat("radius", _this.radius);
  72582. effect.setTexture("depthSampler", _this._depthTexture);
  72583. if (_this._firstUpdate) {
  72584. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72585. _this._firstUpdate = false;
  72586. }
  72587. };
  72588. };
  72589. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72590. this._firstUpdate = true;
  72591. _super.prototype._rebuild.call(this);
  72592. };
  72593. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72594. var numSamples = this.samples;
  72595. var result = [];
  72596. var vector, scale;
  72597. var rand = function (min, max) {
  72598. return Math.random() * (max - min) + min;
  72599. };
  72600. var i = 0;
  72601. while (i < numSamples) {
  72602. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72603. vector.normalize();
  72604. scale = i / numSamples;
  72605. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72606. vector.scaleInPlace(scale);
  72607. result.push(vector.x, vector.y, vector.z);
  72608. i++;
  72609. }
  72610. return result;
  72611. };
  72612. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72613. var _this = this;
  72614. var numSamples = this.samples;
  72615. this._sampleSphere = this._generateHemisphere();
  72616. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72617. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72618. "base", "range", "projection", "near", "far", "texelSize",
  72619. "xViewport", "yViewport", "maxZ", "minZAspect"
  72620. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72621. this._ssaoPostProcess.onApply = function (effect) {
  72622. if (_this._firstUpdate) {
  72623. effect.setArray3("sampleSphere", _this._sampleSphere);
  72624. effect.setFloat("randTextureTiles", 4.0);
  72625. }
  72626. if (!_this._scene.activeCamera) {
  72627. return;
  72628. }
  72629. effect.setFloat("samplesFactor", 1 / _this.samples);
  72630. effect.setFloat("totalStrength", _this.totalStrength);
  72631. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72632. effect.setFloat("radius", _this.radius);
  72633. effect.setFloat("maxZ", _this.maxZ);
  72634. effect.setFloat("minZAspect", _this.minZAspect);
  72635. effect.setFloat("base", _this.base);
  72636. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72637. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72638. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72639. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72640. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72641. effect.setTexture("textureSampler", _this._depthTexture);
  72642. effect.setTexture("normalSampler", _this._normalTexture);
  72643. effect.setTexture("randomSampler", _this._randomTexture);
  72644. };
  72645. };
  72646. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72647. var _this = this;
  72648. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72649. this._ssaoCombinePostProcess.onApply = function (effect) {
  72650. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72651. };
  72652. };
  72653. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72654. var size = 512;
  72655. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72656. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72657. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72658. var context = this._randomTexture.getContext();
  72659. var rand = function (min, max) {
  72660. return Math.random() * (max - min) + min;
  72661. };
  72662. var randVector = BABYLON.Vector3.Zero();
  72663. for (var x = 0; x < size; x++) {
  72664. for (var y = 0; y < size; y++) {
  72665. randVector.x = rand(0.0, 1.0);
  72666. randVector.y = rand(0.0, 1.0);
  72667. randVector.z = 0.0;
  72668. randVector.normalize();
  72669. randVector.scaleInPlace(255);
  72670. randVector.x = Math.floor(randVector.x);
  72671. randVector.y = Math.floor(randVector.y);
  72672. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72673. context.fillRect(x, y, 1, 1);
  72674. }
  72675. }
  72676. this._randomTexture.update(false);
  72677. };
  72678. __decorate([
  72679. BABYLON.serialize()
  72680. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72681. __decorate([
  72682. BABYLON.serialize()
  72683. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72684. __decorate([
  72685. BABYLON.serialize()
  72686. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72687. __decorate([
  72688. BABYLON.serialize("samples")
  72689. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72690. __decorate([
  72691. BABYLON.serialize("expensiveBlur")
  72692. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72693. __decorate([
  72694. BABYLON.serialize()
  72695. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72696. __decorate([
  72697. BABYLON.serialize()
  72698. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72699. return SSAO2RenderingPipeline;
  72700. }(BABYLON.PostProcessRenderPipeline));
  72701. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72702. })(BABYLON || (BABYLON = {}));
  72703. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72704. // BABYLON.JS Chromatic Aberration GLSL Shader
  72705. // Author: Olivier Guyot
  72706. // Separates very slightly R, G and B colors on the edges of the screen
  72707. // Inspired by Francois Tarlier & Martins Upitis
  72708. var BABYLON;
  72709. (function (BABYLON) {
  72710. var LensRenderingPipeline = /** @class */ (function (_super) {
  72711. __extends(LensRenderingPipeline, _super);
  72712. /**
  72713. * @constructor
  72714. *
  72715. * Effect parameters are as follow:
  72716. * {
  72717. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72718. * edge_blur: number; // from 0 to x (1 for realism)
  72719. * distortion: number; // from 0 to x (1 for realism)
  72720. * grain_amount: number; // from 0 to 1
  72721. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72722. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72723. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72724. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72725. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72726. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72727. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72728. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72729. * }
  72730. * Note: if an effect parameter is unset, effect is disabled
  72731. *
  72732. * @param {string} name - The rendering pipeline name
  72733. * @param {object} parameters - An object containing all parameters (see above)
  72734. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72735. * @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)
  72736. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72737. */
  72738. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72739. if (ratio === void 0) { ratio = 1.0; }
  72740. var _this = _super.call(this, scene.getEngine(), name) || this;
  72741. // Lens effects can be of the following:
  72742. // - chromatic aberration (slight shift of RGB colors)
  72743. // - blur on the edge of the lens
  72744. // - lens distortion
  72745. // - depth-of-field blur & highlights enhancing
  72746. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72747. // - grain effect (noise or custom texture)
  72748. // Two additional texture samplers are needed:
  72749. // - depth map (for depth-of-field)
  72750. // - grain texture
  72751. /**
  72752. * The chromatic aberration PostProcess id in the pipeline
  72753. */
  72754. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72755. /**
  72756. * The highlights enhancing PostProcess id in the pipeline
  72757. */
  72758. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72759. /**
  72760. * The depth-of-field PostProcess id in the pipeline
  72761. */
  72762. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72763. _this._scene = scene;
  72764. // Fetch texture samplers
  72765. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72766. if (parameters.grain_texture) {
  72767. _this._grainTexture = parameters.grain_texture;
  72768. }
  72769. else {
  72770. _this._createGrainTexture();
  72771. }
  72772. // save parameters
  72773. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72774. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72775. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72776. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72777. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72778. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72779. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72780. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72781. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72782. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72783. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72784. // Create effects
  72785. _this._createChromaticAberrationPostProcess(ratio);
  72786. _this._createHighlightsPostProcess(ratio);
  72787. _this._createDepthOfFieldPostProcess(ratio / 4);
  72788. // Set up pipeline
  72789. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72790. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72791. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72792. if (_this._highlightsGain === -1) {
  72793. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72794. }
  72795. // Finish
  72796. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72797. if (cameras) {
  72798. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72799. }
  72800. return _this;
  72801. }
  72802. // public methods (self explanatory)
  72803. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72804. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72805. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72806. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72807. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72808. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72809. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72810. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72811. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72812. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72813. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72814. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72815. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72816. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72817. };
  72818. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72819. this._highlightsPostProcess.updateEffect();
  72820. };
  72821. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72822. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72823. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72824. this._highlightsGain = amount;
  72825. };
  72826. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72827. if (this._highlightsGain === -1) {
  72828. this._highlightsGain = 1.0;
  72829. }
  72830. this._highlightsThreshold = amount;
  72831. };
  72832. LensRenderingPipeline.prototype.disableHighlights = function () {
  72833. this._highlightsGain = -1;
  72834. };
  72835. /**
  72836. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72837. */
  72838. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72839. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72840. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72841. this._chromaticAberrationPostProcess = null;
  72842. this._highlightsPostProcess = null;
  72843. this._depthOfFieldPostProcess = null;
  72844. this._grainTexture.dispose();
  72845. if (disableDepthRender)
  72846. this._scene.disableDepthRenderer();
  72847. };
  72848. // colors shifting and distortion
  72849. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72850. var _this = this;
  72851. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72852. [], // samplers
  72853. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72854. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72855. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72856. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72857. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72858. effect.setFloat('radialIntensity', 1);
  72859. effect.setFloat2('direction', 17, 17);
  72860. effect.setFloat2('centerPosition', 0.5, 0.5);
  72861. };
  72862. };
  72863. // highlights enhancing
  72864. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72865. var _this = this;
  72866. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72867. [], // samplers
  72868. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72869. this._highlightsPostProcess.onApply = function (effect) {
  72870. effect.setFloat('gain', _this._highlightsGain);
  72871. effect.setFloat('threshold', _this._highlightsThreshold);
  72872. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72873. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72874. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72875. };
  72876. };
  72877. // colors shifting and distortion
  72878. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72879. var _this = this;
  72880. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72881. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72882. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72883. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72884. this._depthOfFieldPostProcess.onApply = function (effect) {
  72885. effect.setTexture("depthSampler", _this._depthTexture);
  72886. effect.setTexture("grainSampler", _this._grainTexture);
  72887. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72888. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72889. effect.setFloat('grain_amount', _this._grainAmount);
  72890. effect.setBool('blur_noise', _this._blurNoise);
  72891. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72892. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72893. effect.setFloat('distortion', _this._distortion);
  72894. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72895. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72896. effect.setFloat('aperture', _this._dofAperture);
  72897. effect.setFloat('darken', _this._dofDarken);
  72898. effect.setFloat('edge_blur', _this._edgeBlur);
  72899. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72900. if (_this._scene.activeCamera) {
  72901. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72902. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72903. }
  72904. };
  72905. };
  72906. // creates a black and white random noise texture, 512x512
  72907. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72908. var size = 512;
  72909. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72910. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72911. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72912. var context = this._grainTexture.getContext();
  72913. var rand = function (min, max) {
  72914. return Math.random() * (max - min) + min;
  72915. };
  72916. var value;
  72917. for (var x = 0; x < size; x++) {
  72918. for (var y = 0; y < size; y++) {
  72919. value = Math.floor(rand(0.42, 0.58) * 255);
  72920. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72921. context.fillRect(x, y, 1, 1);
  72922. }
  72923. }
  72924. this._grainTexture.update(false);
  72925. };
  72926. return LensRenderingPipeline;
  72927. }(BABYLON.PostProcessRenderPipeline));
  72928. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72929. })(BABYLON || (BABYLON = {}));
  72930. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72931. var BABYLON;
  72932. (function (BABYLON) {
  72933. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72934. __extends(StandardRenderingPipeline, _super);
  72935. /**
  72936. * @constructor
  72937. * @param {string} name - The rendering pipeline name
  72938. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72939. * @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)
  72940. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72941. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72942. */
  72943. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72944. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72945. var _this = _super.call(this, scene.getEngine(), name) || this;
  72946. _this.downSampleX4PostProcess = null;
  72947. _this.brightPassPostProcess = null;
  72948. _this.blurHPostProcesses = [];
  72949. _this.blurVPostProcesses = [];
  72950. _this.textureAdderPostProcess = null;
  72951. _this.volumetricLightPostProcess = null;
  72952. _this.volumetricLightSmoothXPostProcess = null;
  72953. _this.volumetricLightSmoothYPostProcess = null;
  72954. _this.volumetricLightMergePostProces = null;
  72955. _this.volumetricLightFinalPostProcess = null;
  72956. _this.luminancePostProcess = null;
  72957. _this.luminanceDownSamplePostProcesses = [];
  72958. _this.hdrPostProcess = null;
  72959. _this.textureAdderFinalPostProcess = null;
  72960. _this.lensFlareFinalPostProcess = null;
  72961. _this.hdrFinalPostProcess = null;
  72962. _this.lensFlarePostProcess = null;
  72963. _this.lensFlareComposePostProcess = null;
  72964. _this.motionBlurPostProcess = null;
  72965. _this.depthOfFieldPostProcess = null;
  72966. // Values
  72967. _this.brightThreshold = 1.0;
  72968. _this.blurWidth = 512.0;
  72969. _this.horizontalBlur = false;
  72970. _this.exposure = 1.0;
  72971. _this.lensTexture = null;
  72972. _this.volumetricLightCoefficient = 0.2;
  72973. _this.volumetricLightPower = 4.0;
  72974. _this.volumetricLightBlurScale = 64.0;
  72975. _this.sourceLight = null;
  72976. _this.hdrMinimumLuminance = 1.0;
  72977. _this.hdrDecreaseRate = 0.5;
  72978. _this.hdrIncreaseRate = 0.5;
  72979. _this.lensColorTexture = null;
  72980. _this.lensFlareStrength = 20.0;
  72981. _this.lensFlareGhostDispersal = 1.4;
  72982. _this.lensFlareHaloWidth = 0.7;
  72983. _this.lensFlareDistortionStrength = 16.0;
  72984. _this.lensStarTexture = null;
  72985. _this.lensFlareDirtTexture = null;
  72986. _this.depthOfFieldDistance = 10.0;
  72987. _this.depthOfFieldBlurWidth = 64.0;
  72988. _this.motionStrength = 1.0;
  72989. // IAnimatable
  72990. _this.animations = [];
  72991. _this._currentDepthOfFieldSource = null;
  72992. _this._hdrCurrentLuminance = 1.0;
  72993. // Getters and setters
  72994. _this._bloomEnabled = true;
  72995. _this._depthOfFieldEnabled = false;
  72996. _this._vlsEnabled = false;
  72997. _this._lensFlareEnabled = false;
  72998. _this._hdrEnabled = false;
  72999. _this._motionBlurEnabled = false;
  73000. _this._motionBlurSamples = 64.0;
  73001. _this._volumetricLightStepsCount = 50.0;
  73002. _this._cameras = cameras || [];
  73003. // Initialize
  73004. _this._scene = scene;
  73005. _this._basePostProcess = originalPostProcess;
  73006. _this._ratio = ratio;
  73007. // Misc
  73008. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73009. // Finish
  73010. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73011. _this._buildPipeline();
  73012. return _this;
  73013. }
  73014. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73015. get: function () {
  73016. return this._bloomEnabled;
  73017. },
  73018. set: function (enabled) {
  73019. if (this._bloomEnabled === enabled) {
  73020. return;
  73021. }
  73022. this._bloomEnabled = enabled;
  73023. this._buildPipeline();
  73024. },
  73025. enumerable: true,
  73026. configurable: true
  73027. });
  73028. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73029. get: function () {
  73030. return this._depthOfFieldEnabled;
  73031. },
  73032. set: function (enabled) {
  73033. if (this._depthOfFieldEnabled === enabled) {
  73034. return;
  73035. }
  73036. this._depthOfFieldEnabled = enabled;
  73037. this._buildPipeline();
  73038. },
  73039. enumerable: true,
  73040. configurable: true
  73041. });
  73042. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73043. get: function () {
  73044. return this._lensFlareEnabled;
  73045. },
  73046. set: function (enabled) {
  73047. if (this._lensFlareEnabled === enabled) {
  73048. return;
  73049. }
  73050. this._lensFlareEnabled = enabled;
  73051. this._buildPipeline();
  73052. },
  73053. enumerable: true,
  73054. configurable: true
  73055. });
  73056. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73057. get: function () {
  73058. return this._hdrEnabled;
  73059. },
  73060. set: function (enabled) {
  73061. if (this._hdrEnabled === enabled) {
  73062. return;
  73063. }
  73064. this._hdrEnabled = enabled;
  73065. this._buildPipeline();
  73066. },
  73067. enumerable: true,
  73068. configurable: true
  73069. });
  73070. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73071. get: function () {
  73072. return this._vlsEnabled;
  73073. },
  73074. set: function (enabled) {
  73075. if (this._vlsEnabled === enabled) {
  73076. return;
  73077. }
  73078. if (enabled) {
  73079. var geometry = this._scene.enableGeometryBufferRenderer();
  73080. if (!geometry) {
  73081. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73082. return;
  73083. }
  73084. }
  73085. this._vlsEnabled = enabled;
  73086. this._buildPipeline();
  73087. },
  73088. enumerable: true,
  73089. configurable: true
  73090. });
  73091. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73092. get: function () {
  73093. return this._motionBlurEnabled;
  73094. },
  73095. set: function (enabled) {
  73096. if (this._motionBlurEnabled === enabled) {
  73097. return;
  73098. }
  73099. this._motionBlurEnabled = enabled;
  73100. this._buildPipeline();
  73101. },
  73102. enumerable: true,
  73103. configurable: true
  73104. });
  73105. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73106. get: function () {
  73107. return this._volumetricLightStepsCount;
  73108. },
  73109. set: function (count) {
  73110. if (this.volumetricLightPostProcess) {
  73111. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73112. }
  73113. this._volumetricLightStepsCount = count;
  73114. },
  73115. enumerable: true,
  73116. configurable: true
  73117. });
  73118. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73119. get: function () {
  73120. return this._motionBlurSamples;
  73121. },
  73122. set: function (samples) {
  73123. if (this.motionBlurPostProcess) {
  73124. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73125. }
  73126. this._motionBlurSamples = samples;
  73127. },
  73128. enumerable: true,
  73129. configurable: true
  73130. });
  73131. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73132. var _this = this;
  73133. var ratio = this._ratio;
  73134. var scene = this._scene;
  73135. this._disposePostProcesses();
  73136. this._reset();
  73137. // Create pass post-process
  73138. if (!this._basePostProcess) {
  73139. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73140. this.originalPostProcess.onApply = function (effect) {
  73141. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73142. };
  73143. }
  73144. else {
  73145. this.originalPostProcess = this._basePostProcess;
  73146. }
  73147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73148. this._currentDepthOfFieldSource = this.originalPostProcess;
  73149. if (this._vlsEnabled) {
  73150. // Create volumetric light
  73151. this._createVolumetricLightPostProcess(scene, ratio);
  73152. // Create volumetric light final post-process
  73153. 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);
  73154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73155. }
  73156. if (this._bloomEnabled) {
  73157. // Create down sample X4 post-process
  73158. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73159. // Create bright pass post-process
  73160. this._createBrightPassPostProcess(scene, ratio / 2);
  73161. // Create gaussian blur post-processes (down sampling blurs)
  73162. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73163. // Create texture adder post-process
  73164. this._createTextureAdderPostProcess(scene, ratio);
  73165. // Create depth-of-field source post-process
  73166. 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);
  73167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73168. }
  73169. if (this._lensFlareEnabled) {
  73170. // Create lens flare post-process
  73171. this._createLensFlarePostProcess(scene, ratio);
  73172. // Create depth-of-field source post-process post lens-flare and disable it now
  73173. 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);
  73174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73175. }
  73176. if (this._hdrEnabled) {
  73177. // Create luminance
  73178. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73179. // Create HDR
  73180. this._createHdrPostProcess(scene, ratio);
  73181. // Create depth-of-field source post-process post hdr and disable it now
  73182. 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);
  73183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73184. }
  73185. if (this._depthOfFieldEnabled) {
  73186. // Create gaussian blur used by depth-of-field
  73187. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73188. // Create depth-of-field post-process
  73189. this._createDepthOfFieldPostProcess(scene, ratio);
  73190. }
  73191. if (this._motionBlurEnabled) {
  73192. // Create motion blur post-process
  73193. this._createMotionBlurPostProcess(scene, ratio);
  73194. }
  73195. if (this._cameras !== null) {
  73196. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73197. }
  73198. };
  73199. // Down Sample X4 Post-Processs
  73200. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73201. var _this = this;
  73202. var downSampleX4Offsets = new Array(32);
  73203. 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);
  73204. this.downSampleX4PostProcess.onApply = function (effect) {
  73205. var id = 0;
  73206. var width = _this.downSampleX4PostProcess.width;
  73207. var height = _this.downSampleX4PostProcess.height;
  73208. for (var i = -2; i < 2; i++) {
  73209. for (var j = -2; j < 2; j++) {
  73210. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73211. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73212. id += 2;
  73213. }
  73214. }
  73215. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73216. };
  73217. // Add to pipeline
  73218. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73219. };
  73220. // Brightpass Post-Process
  73221. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73222. var _this = this;
  73223. var brightOffsets = new Array(8);
  73224. 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);
  73225. this.brightPassPostProcess.onApply = function (effect) {
  73226. var sU = (1.0 / _this.brightPassPostProcess.width);
  73227. var sV = (1.0 / _this.brightPassPostProcess.height);
  73228. brightOffsets[0] = -0.5 * sU;
  73229. brightOffsets[1] = 0.5 * sV;
  73230. brightOffsets[2] = 0.5 * sU;
  73231. brightOffsets[3] = 0.5 * sV;
  73232. brightOffsets[4] = -0.5 * sU;
  73233. brightOffsets[5] = -0.5 * sV;
  73234. brightOffsets[6] = 0.5 * sU;
  73235. brightOffsets[7] = -0.5 * sV;
  73236. effect.setArray2("dsOffsets", brightOffsets);
  73237. effect.setFloat("brightThreshold", _this.brightThreshold);
  73238. };
  73239. // Add to pipeline
  73240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73241. };
  73242. // Create blur H&V post-processes
  73243. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73244. var _this = this;
  73245. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73246. var engine = scene.getEngine();
  73247. 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);
  73248. 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);
  73249. blurX.onActivateObservable.add(function () {
  73250. var dw = blurX.width / engine.getRenderWidth();
  73251. blurX.kernel = _this[blurWidthKey] * dw;
  73252. });
  73253. blurY.onActivateObservable.add(function () {
  73254. var dw = blurY.height / engine.getRenderHeight();
  73255. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73256. });
  73257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73259. this.blurHPostProcesses.push(blurX);
  73260. this.blurVPostProcesses.push(blurY);
  73261. };
  73262. // Create texture adder post-process
  73263. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73264. var _this = this;
  73265. 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);
  73266. this.textureAdderPostProcess.onApply = function (effect) {
  73267. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73268. effect.setTexture("lensSampler", _this.lensTexture);
  73269. effect.setFloat("exposure", _this.exposure);
  73270. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73271. };
  73272. // Add to pipeline
  73273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73274. };
  73275. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73276. var _this = this;
  73277. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73278. geometryRenderer.enablePosition = true;
  73279. var geometry = geometryRenderer.getGBuffer();
  73280. // Base post-process
  73281. 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));
  73282. var depthValues = BABYLON.Vector2.Zero();
  73283. this.volumetricLightPostProcess.onApply = function (effect) {
  73284. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73285. var generator = _this.sourceLight.getShadowGenerator();
  73286. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73287. effect.setTexture("positionSampler", geometry.textures[2]);
  73288. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73289. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73290. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73291. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73292. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73293. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73294. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73295. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73296. effect.setVector2("depthValues", depthValues);
  73297. }
  73298. };
  73299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73300. // Smooth
  73301. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73302. // Merge
  73303. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73304. this.volumetricLightMergePostProces.onApply = function (effect) {
  73305. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73306. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73307. };
  73308. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73309. };
  73310. // Create luminance
  73311. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73312. var _this = this;
  73313. // Create luminance
  73314. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73315. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73316. var offsets = [];
  73317. this.luminancePostProcess.onApply = function (effect) {
  73318. var sU = (1.0 / _this.luminancePostProcess.width);
  73319. var sV = (1.0 / _this.luminancePostProcess.height);
  73320. offsets[0] = -0.5 * sU;
  73321. offsets[1] = 0.5 * sV;
  73322. offsets[2] = 0.5 * sU;
  73323. offsets[3] = 0.5 * sV;
  73324. offsets[4] = -0.5 * sU;
  73325. offsets[5] = -0.5 * sV;
  73326. offsets[6] = 0.5 * sU;
  73327. offsets[7] = -0.5 * sV;
  73328. effect.setArray2("lumOffsets", offsets);
  73329. };
  73330. // Add to pipeline
  73331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73332. // Create down sample luminance
  73333. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73334. var size = Math.pow(3, i);
  73335. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73336. if (i === 0) {
  73337. defines += "#define FINAL_DOWN_SAMPLER";
  73338. }
  73339. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73340. this.luminanceDownSamplePostProcesses.push(postProcess);
  73341. }
  73342. // Create callbacks and add effects
  73343. var lastLuminance = this.luminancePostProcess;
  73344. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73345. var downSampleOffsets = new Array(18);
  73346. pp.onApply = function (effect) {
  73347. if (!lastLuminance) {
  73348. return;
  73349. }
  73350. var id = 0;
  73351. for (var x = -1; x < 2; x++) {
  73352. for (var y = -1; y < 2; y++) {
  73353. downSampleOffsets[id] = x / lastLuminance.width;
  73354. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73355. id += 2;
  73356. }
  73357. }
  73358. effect.setArray2("dsOffsets", downSampleOffsets);
  73359. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73360. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73361. lastLuminance = _this.luminancePostProcess;
  73362. }
  73363. else {
  73364. lastLuminance = pp;
  73365. }
  73366. };
  73367. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73368. pp.onAfterRender = function (effect) {
  73369. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73370. 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);
  73371. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73372. };
  73373. }
  73374. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73375. });
  73376. };
  73377. // Create HDR post-process
  73378. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73379. var _this = this;
  73380. 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);
  73381. var outputLiminance = 1;
  73382. var time = 0;
  73383. var lastTime = 0;
  73384. this.hdrPostProcess.onApply = function (effect) {
  73385. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73386. time += scene.getEngine().getDeltaTime();
  73387. if (outputLiminance < 0) {
  73388. outputLiminance = _this._hdrCurrentLuminance;
  73389. }
  73390. else {
  73391. var dt = (lastTime - time) / 1000.0;
  73392. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73393. outputLiminance += _this.hdrDecreaseRate * dt;
  73394. }
  73395. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73396. outputLiminance -= _this.hdrIncreaseRate * dt;
  73397. }
  73398. else {
  73399. outputLiminance = _this._hdrCurrentLuminance;
  73400. }
  73401. }
  73402. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73403. effect.setFloat("averageLuminance", outputLiminance);
  73404. lastTime = time;
  73405. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73406. };
  73407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73408. };
  73409. // Create lens flare post-process
  73410. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73411. var _this = this;
  73412. 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);
  73413. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73414. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73415. 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);
  73416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73417. var resolution = new BABYLON.Vector2(0, 0);
  73418. // Lens flare
  73419. this.lensFlarePostProcess.onApply = function (effect) {
  73420. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73421. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73422. effect.setFloat("strength", _this.lensFlareStrength);
  73423. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73424. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73425. // Shift
  73426. resolution.x = _this.lensFlarePostProcess.width;
  73427. resolution.y = _this.lensFlarePostProcess.height;
  73428. effect.setVector2("resolution", resolution);
  73429. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73430. };
  73431. // Compose
  73432. 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);
  73433. 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);
  73434. this.lensFlareComposePostProcess.onApply = function (effect) {
  73435. if (!_this._scene.activeCamera) {
  73436. return;
  73437. }
  73438. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73439. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73440. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73441. // Lens start rotation matrix
  73442. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73443. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73444. 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));
  73445. camRot *= 4.0;
  73446. 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);
  73447. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73448. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73449. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73450. };
  73451. };
  73452. // Create depth-of-field post-process
  73453. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73454. var _this = this;
  73455. 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);
  73456. this.depthOfFieldPostProcess.onApply = function (effect) {
  73457. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73458. effect.setTexture("depthSampler", _this._getDepthTexture());
  73459. effect.setFloat("distance", _this.depthOfFieldDistance);
  73460. };
  73461. // Add to pipeline
  73462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73463. };
  73464. // Create motion blur post-process
  73465. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73466. var _this = this;
  73467. 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);
  73468. var motionScale = 0;
  73469. var prevViewProjection = BABYLON.Matrix.Identity();
  73470. var invViewProjection = BABYLON.Matrix.Identity();
  73471. var viewProjection = BABYLON.Matrix.Identity();
  73472. var screenSize = BABYLON.Vector2.Zero();
  73473. this.motionBlurPostProcess.onApply = function (effect) {
  73474. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73475. viewProjection.invertToRef(invViewProjection);
  73476. effect.setMatrix("inverseViewProjection", invViewProjection);
  73477. effect.setMatrix("prevViewProjection", prevViewProjection);
  73478. prevViewProjection = viewProjection;
  73479. screenSize.x = _this.motionBlurPostProcess.width;
  73480. screenSize.y = _this.motionBlurPostProcess.height;
  73481. effect.setVector2("screenSize", screenSize);
  73482. motionScale = scene.getEngine().getFps() / 60.0;
  73483. effect.setFloat("motionScale", motionScale);
  73484. effect.setFloat("motionStrength", _this.motionStrength);
  73485. effect.setTexture("depthSampler", _this._getDepthTexture());
  73486. };
  73487. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73488. };
  73489. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73490. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73491. var renderer = this._scene.enableGeometryBufferRenderer();
  73492. return renderer.getGBuffer().textures[0];
  73493. }
  73494. return this._scene.enableDepthRenderer().getDepthMap();
  73495. };
  73496. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73497. for (var i = 0; i < this._cameras.length; i++) {
  73498. var camera = this._cameras[i];
  73499. if (this.originalPostProcess) {
  73500. this.originalPostProcess.dispose(camera);
  73501. }
  73502. if (this.downSampleX4PostProcess) {
  73503. this.downSampleX4PostProcess.dispose(camera);
  73504. }
  73505. if (this.brightPassPostProcess) {
  73506. this.brightPassPostProcess.dispose(camera);
  73507. }
  73508. if (this.textureAdderPostProcess) {
  73509. this.textureAdderPostProcess.dispose(camera);
  73510. }
  73511. if (this.textureAdderFinalPostProcess) {
  73512. this.textureAdderFinalPostProcess.dispose(camera);
  73513. }
  73514. if (this.volumetricLightPostProcess) {
  73515. this.volumetricLightPostProcess.dispose(camera);
  73516. }
  73517. if (this.volumetricLightSmoothXPostProcess) {
  73518. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73519. }
  73520. if (this.volumetricLightSmoothYPostProcess) {
  73521. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73522. }
  73523. if (this.volumetricLightMergePostProces) {
  73524. this.volumetricLightMergePostProces.dispose(camera);
  73525. }
  73526. if (this.volumetricLightFinalPostProcess) {
  73527. this.volumetricLightFinalPostProcess.dispose(camera);
  73528. }
  73529. if (this.lensFlarePostProcess) {
  73530. this.lensFlarePostProcess.dispose(camera);
  73531. }
  73532. if (this.lensFlareComposePostProcess) {
  73533. this.lensFlareComposePostProcess.dispose(camera);
  73534. }
  73535. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73536. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73537. }
  73538. if (this.luminancePostProcess) {
  73539. this.luminancePostProcess.dispose(camera);
  73540. }
  73541. if (this.hdrPostProcess) {
  73542. this.hdrPostProcess.dispose(camera);
  73543. }
  73544. if (this.hdrFinalPostProcess) {
  73545. this.hdrFinalPostProcess.dispose(camera);
  73546. }
  73547. if (this.depthOfFieldPostProcess) {
  73548. this.depthOfFieldPostProcess.dispose(camera);
  73549. }
  73550. if (this.motionBlurPostProcess) {
  73551. this.motionBlurPostProcess.dispose(camera);
  73552. }
  73553. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73554. this.blurHPostProcesses[j].dispose(camera);
  73555. }
  73556. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73557. this.blurVPostProcesses[j].dispose(camera);
  73558. }
  73559. }
  73560. this.originalPostProcess = null;
  73561. this.downSampleX4PostProcess = null;
  73562. this.brightPassPostProcess = null;
  73563. this.textureAdderPostProcess = null;
  73564. this.textureAdderFinalPostProcess = null;
  73565. this.volumetricLightPostProcess = null;
  73566. this.volumetricLightSmoothXPostProcess = null;
  73567. this.volumetricLightSmoothYPostProcess = null;
  73568. this.volumetricLightMergePostProces = null;
  73569. this.volumetricLightFinalPostProcess = null;
  73570. this.lensFlarePostProcess = null;
  73571. this.lensFlareComposePostProcess = null;
  73572. this.luminancePostProcess = null;
  73573. this.hdrPostProcess = null;
  73574. this.hdrFinalPostProcess = null;
  73575. this.depthOfFieldPostProcess = null;
  73576. this.motionBlurPostProcess = null;
  73577. this.luminanceDownSamplePostProcesses = [];
  73578. this.blurHPostProcesses = [];
  73579. this.blurVPostProcesses = [];
  73580. };
  73581. // Dispose
  73582. StandardRenderingPipeline.prototype.dispose = function () {
  73583. this._disposePostProcesses();
  73584. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73585. _super.prototype.dispose.call(this);
  73586. };
  73587. // Serialize rendering pipeline
  73588. StandardRenderingPipeline.prototype.serialize = function () {
  73589. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73590. serializationObject.customType = "StandardRenderingPipeline";
  73591. return serializationObject;
  73592. };
  73593. /**
  73594. * Static members
  73595. */
  73596. // Parse serialized pipeline
  73597. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73598. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73599. };
  73600. // Luminance steps
  73601. StandardRenderingPipeline.LuminanceSteps = 6;
  73602. __decorate([
  73603. BABYLON.serialize()
  73604. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73605. __decorate([
  73606. BABYLON.serialize()
  73607. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73608. __decorate([
  73609. BABYLON.serialize()
  73610. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73611. __decorate([
  73612. BABYLON.serialize()
  73613. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73614. __decorate([
  73615. BABYLON.serializeAsTexture("lensTexture")
  73616. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73617. __decorate([
  73618. BABYLON.serialize()
  73619. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73620. __decorate([
  73621. BABYLON.serialize()
  73622. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73623. __decorate([
  73624. BABYLON.serialize()
  73625. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73626. __decorate([
  73627. BABYLON.serialize()
  73628. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73629. __decorate([
  73630. BABYLON.serialize()
  73631. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73632. __decorate([
  73633. BABYLON.serialize()
  73634. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73635. __decorate([
  73636. BABYLON.serializeAsTexture("lensColorTexture")
  73637. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73638. __decorate([
  73639. BABYLON.serialize()
  73640. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73641. __decorate([
  73642. BABYLON.serialize()
  73643. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73644. __decorate([
  73645. BABYLON.serialize()
  73646. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73647. __decorate([
  73648. BABYLON.serialize()
  73649. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73650. __decorate([
  73651. BABYLON.serializeAsTexture("lensStarTexture")
  73652. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73653. __decorate([
  73654. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73655. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73656. __decorate([
  73657. BABYLON.serialize()
  73658. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73659. __decorate([
  73660. BABYLON.serialize()
  73661. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73662. __decorate([
  73663. BABYLON.serialize()
  73664. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73665. __decorate([
  73666. BABYLON.serialize()
  73667. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73668. __decorate([
  73669. BABYLON.serialize()
  73670. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73671. __decorate([
  73672. BABYLON.serialize()
  73673. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73674. __decorate([
  73675. BABYLON.serialize()
  73676. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73677. __decorate([
  73678. BABYLON.serialize()
  73679. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73680. __decorate([
  73681. BABYLON.serialize()
  73682. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73683. __decorate([
  73684. BABYLON.serialize()
  73685. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73686. __decorate([
  73687. BABYLON.serialize()
  73688. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73689. __decorate([
  73690. BABYLON.serialize()
  73691. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73692. return StandardRenderingPipeline;
  73693. }(BABYLON.PostProcessRenderPipeline));
  73694. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73695. })(BABYLON || (BABYLON = {}));
  73696. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73697. var BABYLON;
  73698. (function (BABYLON) {
  73699. var FxaaPostProcess = /** @class */ (function (_super) {
  73700. __extends(FxaaPostProcess, _super);
  73701. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73702. if (camera === void 0) { camera = null; }
  73703. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73704. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73705. _this.onApplyObservable.add(function (effect) {
  73706. var texelSize = _this.texelSize;
  73707. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73708. });
  73709. return _this;
  73710. }
  73711. return FxaaPostProcess;
  73712. }(BABYLON.PostProcess));
  73713. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73714. })(BABYLON || (BABYLON = {}));
  73715. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73716. var BABYLON;
  73717. (function (BABYLON) {
  73718. /**
  73719. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73720. */
  73721. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73722. __extends(ChromaticAberrationPostProcess, _super);
  73723. /**
  73724. * Creates a new instance ChromaticAberrationPostProcess
  73725. * @param name The name of the effect.
  73726. * @param screenWidth The width of the screen to apply the effect on.
  73727. * @param screenHeight The height of the screen to apply the effect on.
  73728. * @param options The required width/height ratio to downsize to before computing the render pass.
  73729. * @param camera The camera to apply the render pass to.
  73730. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73731. * @param engine The engine which the post process will be applied. (default: current engine)
  73732. * @param reusable If the post process can be reused on the same frame. (default: false)
  73733. * @param textureType Type of textures used when performing the post process. (default: 0)
  73734. * @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)
  73735. */
  73736. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73738. if (blockCompilation === void 0) { blockCompilation = false; }
  73739. 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;
  73740. /**
  73741. * The amount of seperation of rgb channels (default: 30)
  73742. */
  73743. _this.aberrationAmount = 30;
  73744. /**
  73745. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73746. */
  73747. _this.radialIntensity = 0;
  73748. /**
  73749. * 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))
  73750. */
  73751. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73752. /**
  73753. * 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))
  73754. */
  73755. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73756. _this.onApplyObservable.add(function (effect) {
  73757. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73758. effect.setFloat('screen_width', screenWidth);
  73759. effect.setFloat('screen_height', screenHeight);
  73760. effect.setFloat('radialIntensity', _this.radialIntensity);
  73761. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73762. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73763. });
  73764. return _this;
  73765. }
  73766. return ChromaticAberrationPostProcess;
  73767. }(BABYLON.PostProcess));
  73768. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73769. })(BABYLON || (BABYLON = {}));
  73770. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73771. var BABYLON;
  73772. (function (BABYLON) {
  73773. /**
  73774. * The GrainPostProcess adds noise to the image at mid luminance levels
  73775. */
  73776. var GrainPostProcess = /** @class */ (function (_super) {
  73777. __extends(GrainPostProcess, _super);
  73778. /**
  73779. * Creates a new instance of @see GrainPostProcess
  73780. * @param name The name of the effect.
  73781. * @param options The required width/height ratio to downsize to before computing the render pass.
  73782. * @param camera The camera to apply the render pass to.
  73783. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73784. * @param engine The engine which the post process will be applied. (default: current engine)
  73785. * @param reusable If the post process can be reused on the same frame. (default: false)
  73786. * @param textureType Type of textures used when performing the post process. (default: 0)
  73787. * @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)
  73788. */
  73789. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73790. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73791. if (blockCompilation === void 0) { blockCompilation = false; }
  73792. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73793. /**
  73794. * The intensity of the grain added (default: 30)
  73795. */
  73796. _this.intensity = 30;
  73797. /**
  73798. * If the grain should be randomized on every frame
  73799. */
  73800. _this.animated = false;
  73801. _this.onApplyObservable.add(function (effect) {
  73802. effect.setFloat('intensity', _this.intensity);
  73803. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73804. });
  73805. return _this;
  73806. }
  73807. return GrainPostProcess;
  73808. }(BABYLON.PostProcess));
  73809. BABYLON.GrainPostProcess = GrainPostProcess;
  73810. })(BABYLON || (BABYLON = {}));
  73811. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73812. var BABYLON;
  73813. (function (BABYLON) {
  73814. /**
  73815. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73816. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73817. */
  73818. var SharpenPostProcess = /** @class */ (function (_super) {
  73819. __extends(SharpenPostProcess, _super);
  73820. /**
  73821. * Creates a new instance ConvolutionPostProcess
  73822. * @param name The name of the effect.
  73823. * @param options The required width/height ratio to downsize to before computing the render pass.
  73824. * @param camera The camera to apply the render pass to.
  73825. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73826. * @param engine The engine which the post process will be applied. (default: current engine)
  73827. * @param reusable If the post process can be reused on the same frame. (default: false)
  73828. * @param textureType Type of textures used when performing the post process. (default: 0)
  73829. * @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)
  73830. */
  73831. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73832. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73833. if (blockCompilation === void 0) { blockCompilation = false; }
  73834. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73835. /**
  73836. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73837. */
  73838. _this.colorAmount = 1.0;
  73839. /**
  73840. * How much sharpness should be applied (default: 0.3)
  73841. */
  73842. _this.edgeAmount = 0.3;
  73843. _this.onApply = function (effect) {
  73844. effect.setFloat2("screenSize", _this.width, _this.height);
  73845. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73846. };
  73847. return _this;
  73848. }
  73849. return SharpenPostProcess;
  73850. }(BABYLON.PostProcess));
  73851. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73852. })(BABYLON || (BABYLON = {}));
  73853. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73854. var BABYLON;
  73855. (function (BABYLON) {
  73856. /**
  73857. * The Blur Post Process which blurs an image based on a kernel and direction.
  73858. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73859. */
  73860. var BlurPostProcess = /** @class */ (function (_super) {
  73861. __extends(BlurPostProcess, _super);
  73862. /**
  73863. * Creates a new instance BlurPostProcess
  73864. * @param name The name of the effect.
  73865. * @param direction The direction in which to blur the image.
  73866. * @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.
  73867. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73868. * @param camera The camera to apply the render pass to.
  73869. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73870. * @param engine The engine which the post process will be applied. (default: current engine)
  73871. * @param reusable If the post process can be reused on the same frame. (default: false)
  73872. * @param textureType Type of textures used when performing the post process. (default: 0)
  73873. * @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)
  73874. */
  73875. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73877. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73878. if (defines === void 0) { defines = ""; }
  73879. if (blockCompilation === void 0) { blockCompilation = false; }
  73880. 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;
  73881. _this.direction = direction;
  73882. _this.blockCompilation = blockCompilation;
  73883. _this._packedFloat = false;
  73884. _this._staticDefines = "";
  73885. _this._staticDefines = defines;
  73886. _this.onApplyObservable.add(function (effect) {
  73887. if (_this._outputTexture) {
  73888. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73889. }
  73890. else {
  73891. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73892. }
  73893. });
  73894. _this.kernel = kernel;
  73895. return _this;
  73896. }
  73897. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73898. /**
  73899. * Gets the length in pixels of the blur sample region
  73900. */
  73901. get: function () {
  73902. return this._idealKernel;
  73903. },
  73904. /**
  73905. * Sets the length in pixels of the blur sample region
  73906. */
  73907. set: function (v) {
  73908. if (this._idealKernel === v) {
  73909. return;
  73910. }
  73911. v = Math.max(v, 1);
  73912. this._idealKernel = v;
  73913. this._kernel = this._nearestBestKernel(v);
  73914. if (!this.blockCompilation) {
  73915. this._updateParameters();
  73916. }
  73917. },
  73918. enumerable: true,
  73919. configurable: true
  73920. });
  73921. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73922. /**
  73923. * Gets wether or not the blur is unpacking/repacking floats
  73924. */
  73925. get: function () {
  73926. return this._packedFloat;
  73927. },
  73928. /**
  73929. * Sets wether or not the blur needs to unpack/repack floats
  73930. */
  73931. set: function (v) {
  73932. if (this._packedFloat === v) {
  73933. return;
  73934. }
  73935. this._packedFloat = v;
  73936. if (!this.blockCompilation) {
  73937. this._updateParameters();
  73938. }
  73939. },
  73940. enumerable: true,
  73941. configurable: true
  73942. });
  73943. /**
  73944. * Updates the effect with the current post process compile time values and recompiles the shader.
  73945. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73946. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73947. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73948. * @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
  73949. * @param onCompiled Called when the shader has been compiled.
  73950. * @param onError Called if there is an error when compiling a shader.
  73951. */
  73952. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73953. if (defines === void 0) { defines = null; }
  73954. if (uniforms === void 0) { uniforms = null; }
  73955. if (samplers === void 0) { samplers = null; }
  73956. this._updateParameters(onCompiled, onError);
  73957. };
  73958. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73959. // Generate sampling offsets and weights
  73960. var N = this._kernel;
  73961. var centerIndex = (N - 1) / 2;
  73962. // Generate Gaussian sampling weights over kernel
  73963. var offsets = [];
  73964. var weights = [];
  73965. var totalWeight = 0;
  73966. for (var i = 0; i < N; i++) {
  73967. var u = i / (N - 1);
  73968. var w = this._gaussianWeight(u * 2.0 - 1);
  73969. offsets[i] = (i - centerIndex);
  73970. weights[i] = w;
  73971. totalWeight += w;
  73972. }
  73973. // Normalize weights
  73974. for (var i = 0; i < weights.length; i++) {
  73975. weights[i] /= totalWeight;
  73976. }
  73977. // Optimize: combine samples to take advantage of hardware linear sampling
  73978. // Walk from left to center, combining pairs (symmetrically)
  73979. var linearSamplingWeights = [];
  73980. var linearSamplingOffsets = [];
  73981. var linearSamplingMap = [];
  73982. for (var i = 0; i <= centerIndex; i += 2) {
  73983. var j = Math.min(i + 1, Math.floor(centerIndex));
  73984. var singleCenterSample = i === j;
  73985. if (singleCenterSample) {
  73986. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73987. }
  73988. else {
  73989. var sharedCell = j === centerIndex;
  73990. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73991. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73992. if (offsetLinear === 0) {
  73993. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73994. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73995. }
  73996. else {
  73997. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73998. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73999. }
  74000. }
  74001. }
  74002. for (var i = 0; i < linearSamplingMap.length; i++) {
  74003. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74004. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74005. }
  74006. // Replace with optimized
  74007. offsets = linearSamplingOffsets;
  74008. weights = linearSamplingWeights;
  74009. // Generate shaders
  74010. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74011. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74012. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74013. var defines = "";
  74014. defines += this._staticDefines;
  74015. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74016. if (this._staticDefines.indexOf("DOF") != -1) {
  74017. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74018. varyingCount--;
  74019. }
  74020. for (var i = 0; i < varyingCount; i++) {
  74021. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74022. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74023. }
  74024. var depCount = 0;
  74025. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74026. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74027. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74028. depCount++;
  74029. }
  74030. if (this.packedFloat) {
  74031. defines += "#define PACKEDFLOAT 1";
  74032. }
  74033. this.blockCompilation = false;
  74034. _super.prototype.updateEffect.call(this, defines, null, null, {
  74035. varyingCount: varyingCount,
  74036. depCount: depCount
  74037. }, onCompiled, onError);
  74038. };
  74039. /**
  74040. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74041. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74042. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74043. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74044. * The gaps between physical kernels are compensated for in the weighting of the samples
  74045. * @param idealKernel Ideal blur kernel.
  74046. * @return Nearest best kernel.
  74047. */
  74048. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74049. var v = Math.round(idealKernel);
  74050. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74051. var k = _a[_i];
  74052. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74053. return Math.max(k, 3);
  74054. }
  74055. }
  74056. return Math.max(v, 3);
  74057. };
  74058. /**
  74059. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74060. * @param x The point on the Gaussian distribution to sample.
  74061. * @return the value of the Gaussian function at x.
  74062. */
  74063. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74064. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74065. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74066. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74067. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74068. // truncated at around 1.3% of peak strength.
  74069. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74070. var sigma = (1 / 3);
  74071. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74072. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74073. var weight = (1.0 / denominator) * Math.exp(exponent);
  74074. return weight;
  74075. };
  74076. /**
  74077. * Generates a string that can be used as a floating point number in GLSL.
  74078. * @param x Value to print.
  74079. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74080. * @return GLSL float string.
  74081. */
  74082. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74083. if (decimalFigures === void 0) { decimalFigures = 8; }
  74084. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74085. };
  74086. return BlurPostProcess;
  74087. }(BABYLON.PostProcess));
  74088. BABYLON.BlurPostProcess = BlurPostProcess;
  74089. })(BABYLON || (BABYLON = {}));
  74090. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74091. var BABYLON;
  74092. (function (BABYLON) {
  74093. /**
  74094. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74095. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74096. * based on samples that have a large difference in distance than the center pixel.
  74097. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74098. */
  74099. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74100. __extends(DepthOfFieldBlurPostProcess, _super);
  74101. /**
  74102. * Creates a new instance CircleOfConfusionPostProcess
  74103. * @param name The name of the effect.
  74104. * @param scene The scene the effect belongs to.
  74105. * @param direction The direction the blur should be applied.
  74106. * @param kernel The size of the kernel used to blur.
  74107. * @param options The required width/height ratio to downsize to before computing the render pass.
  74108. * @param camera The camera to apply the render pass to.
  74109. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74110. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74111. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74112. * @param engine The engine which the post process will be applied. (default: current engine)
  74113. * @param reusable If the post process can be reused on the same frame. (default: false)
  74114. * @param textureType Type of textures used when performing the post process. (default: 0)
  74115. * @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)
  74116. */
  74117. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74118. if (imageToBlur === void 0) { imageToBlur = null; }
  74119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74120. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74121. if (blockCompilation === void 0) { blockCompilation = false; }
  74122. 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;
  74123. _this.direction = direction;
  74124. _this.onApplyObservable.add(function (effect) {
  74125. if (imageToBlur != null) {
  74126. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74127. }
  74128. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74129. if (scene.activeCamera) {
  74130. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74131. }
  74132. });
  74133. return _this;
  74134. }
  74135. return DepthOfFieldBlurPostProcess;
  74136. }(BABYLON.BlurPostProcess));
  74137. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74138. })(BABYLON || (BABYLON = {}));
  74139. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74140. var BABYLON;
  74141. (function (BABYLON) {
  74142. /**
  74143. * Options to be set when merging outputs from the default pipeline.
  74144. */
  74145. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74146. function DepthOfFieldMergePostProcessOptions() {
  74147. }
  74148. return DepthOfFieldMergePostProcessOptions;
  74149. }());
  74150. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74151. /**
  74152. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74153. */
  74154. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74155. __extends(DepthOfFieldMergePostProcess, _super);
  74156. /**
  74157. * Creates a new instance of DepthOfFieldMergePostProcess
  74158. * @param name The name of the effect.
  74159. * @param originalFromInput Post process which's input will be used for the merge.
  74160. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74161. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74162. * @param options The required width/height ratio to downsize to before computing the render pass.
  74163. * @param camera The camera to apply the render pass to.
  74164. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74165. * @param engine The engine which the post process will be applied. (default: current engine)
  74166. * @param reusable If the post process can be reused on the same frame. (default: false)
  74167. * @param textureType Type of textures used when performing the post process. (default: 0)
  74168. * @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)
  74169. */
  74170. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74171. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74172. if (blockCompilation === void 0) { blockCompilation = false; }
  74173. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74174. _this.blurSteps = blurSteps;
  74175. _this.onApplyObservable.add(function (effect) {
  74176. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74177. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74178. blurSteps.forEach(function (step, index) {
  74179. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74180. });
  74181. });
  74182. if (!blockCompilation) {
  74183. _this.updateEffect();
  74184. }
  74185. return _this;
  74186. }
  74187. /**
  74188. * Updates the effect with the current post process compile time values and recompiles the shader.
  74189. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74190. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74191. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74192. * @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
  74193. * @param onCompiled Called when the shader has been compiled.
  74194. * @param onError Called if there is an error when compiling a shader.
  74195. */
  74196. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74197. if (defines === void 0) { defines = null; }
  74198. if (uniforms === void 0) { uniforms = null; }
  74199. if (samplers === void 0) { samplers = null; }
  74200. if (!defines) {
  74201. defines = "";
  74202. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74203. }
  74204. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74205. };
  74206. return DepthOfFieldMergePostProcess;
  74207. }(BABYLON.PostProcess));
  74208. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74209. })(BABYLON || (BABYLON = {}));
  74210. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74211. var BABYLON;
  74212. (function (BABYLON) {
  74213. /**
  74214. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74215. */
  74216. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74217. __extends(CircleOfConfusionPostProcess, _super);
  74218. /**
  74219. * Creates a new instance CircleOfConfusionPostProcess
  74220. * @param name The name of the effect.
  74221. * @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.
  74222. * @param options The required width/height ratio to downsize to before computing the render pass.
  74223. * @param camera The camera to apply the render pass to.
  74224. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74225. * @param engine The engine which the post process will be applied. (default: current engine)
  74226. * @param reusable If the post process can be reused on the same frame. (default: false)
  74227. * @param textureType Type of textures used when performing the post process. (default: 0)
  74228. * @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)
  74229. */
  74230. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74231. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74232. if (blockCompilation === void 0) { blockCompilation = false; }
  74233. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74234. /**
  74235. * 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.
  74236. */
  74237. _this.lensSize = 50;
  74238. /**
  74239. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74240. */
  74241. _this.fStop = 1.4;
  74242. /**
  74243. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74244. */
  74245. _this.focusDistance = 2000;
  74246. /**
  74247. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74248. */
  74249. _this.focalLength = 50;
  74250. _this._depthTexture = null;
  74251. _this._depthTexture = depthTexture;
  74252. _this.onApplyObservable.add(function (effect) {
  74253. if (!_this._depthTexture) {
  74254. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74255. return;
  74256. }
  74257. effect.setTexture("depthSampler", _this._depthTexture);
  74258. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74259. var aperture = _this.lensSize / _this.fStop;
  74260. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74261. effect.setFloat('focusDistance', _this.focusDistance);
  74262. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74263. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74264. });
  74265. return _this;
  74266. }
  74267. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74268. /**
  74269. * 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.
  74270. */
  74271. set: function (value) {
  74272. this._depthTexture = value;
  74273. },
  74274. enumerable: true,
  74275. configurable: true
  74276. });
  74277. return CircleOfConfusionPostProcess;
  74278. }(BABYLON.PostProcess));
  74279. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74280. })(BABYLON || (BABYLON = {}));
  74281. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74282. var BABYLON;
  74283. (function (BABYLON) {
  74284. /**
  74285. * Specifies the level of max blur that should be applied when using the depth of field effect
  74286. */
  74287. var DepthOfFieldEffectBlurLevel;
  74288. (function (DepthOfFieldEffectBlurLevel) {
  74289. /**
  74290. * Subtle blur
  74291. */
  74292. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74293. /**
  74294. * Medium blur
  74295. */
  74296. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74297. /**
  74298. * Large blur
  74299. */
  74300. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74301. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74302. ;
  74303. /**
  74304. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74305. */
  74306. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74307. __extends(DepthOfFieldEffect, _super);
  74308. /**
  74309. * Creates a new instance DepthOfFieldEffect
  74310. * @param scene The scene the effect belongs to.
  74311. * @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.
  74312. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74313. * @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)
  74314. */
  74315. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74316. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74317. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74318. if (blockCompilation === void 0) { blockCompilation = false; }
  74319. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74320. return _this._effects;
  74321. }, true) || this;
  74322. /**
  74323. * Internal post processes in depth of field effect
  74324. */
  74325. _this._effects = [];
  74326. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74327. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74328. // 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)
  74329. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74330. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74331. _this._depthOfFieldBlurY = [];
  74332. _this._depthOfFieldBlurX = [];
  74333. var blurCount = 1;
  74334. var kernelSize = 15;
  74335. switch (blurLevel) {
  74336. case DepthOfFieldEffectBlurLevel.High: {
  74337. blurCount = 3;
  74338. kernelSize = 51;
  74339. break;
  74340. }
  74341. case DepthOfFieldEffectBlurLevel.Medium: {
  74342. blurCount = 2;
  74343. kernelSize = 31;
  74344. break;
  74345. }
  74346. default: {
  74347. kernelSize = 15;
  74348. blurCount = 1;
  74349. break;
  74350. }
  74351. }
  74352. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74353. var ratio = 1.0;
  74354. for (var i = 0; i < blurCount; i++) {
  74355. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74356. blurY.autoClear = false;
  74357. ratio = 0.75 / Math.pow(2, i);
  74358. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74359. blurX.autoClear = false;
  74360. _this._depthOfFieldBlurY.push(blurY);
  74361. _this._depthOfFieldBlurX.push(blurX);
  74362. }
  74363. // Set all post processes on the effect.
  74364. _this._effects = [_this._circleOfConfusion];
  74365. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74366. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74367. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74368. }
  74369. // Merge blurred images with original image based on circleOfConfusion
  74370. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74371. _this._dofMerge.autoClear = false;
  74372. _this._effects.push(_this._dofMerge);
  74373. return _this;
  74374. }
  74375. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74376. get: function () {
  74377. return this._circleOfConfusion.focalLength;
  74378. },
  74379. /**
  74380. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74381. */
  74382. set: function (value) {
  74383. this._circleOfConfusion.focalLength = value;
  74384. },
  74385. enumerable: true,
  74386. configurable: true
  74387. });
  74388. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74389. get: function () {
  74390. return this._circleOfConfusion.fStop;
  74391. },
  74392. /**
  74393. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74394. */
  74395. set: function (value) {
  74396. this._circleOfConfusion.fStop = value;
  74397. },
  74398. enumerable: true,
  74399. configurable: true
  74400. });
  74401. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74402. get: function () {
  74403. return this._circleOfConfusion.focusDistance;
  74404. },
  74405. /**
  74406. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74407. */
  74408. set: function (value) {
  74409. this._circleOfConfusion.focusDistance = value;
  74410. },
  74411. enumerable: true,
  74412. configurable: true
  74413. });
  74414. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74415. get: function () {
  74416. return this._circleOfConfusion.lensSize;
  74417. },
  74418. /**
  74419. * 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.
  74420. */
  74421. set: function (value) {
  74422. this._circleOfConfusion.lensSize = value;
  74423. },
  74424. enumerable: true,
  74425. configurable: true
  74426. });
  74427. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74428. /**
  74429. * 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.
  74430. */
  74431. set: function (value) {
  74432. this._circleOfConfusion.depthTexture = value;
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. /**
  74438. * Disposes each of the internal effects for a given camera.
  74439. * @param camera The camera to dispose the effect on.
  74440. */
  74441. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74442. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74443. this._effects[effectIndex].dispose(camera);
  74444. }
  74445. };
  74446. /**
  74447. * Internal
  74448. */
  74449. DepthOfFieldEffect.prototype._updateEffects = function () {
  74450. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74451. this._effects[effectIndex].updateEffect();
  74452. }
  74453. };
  74454. /**
  74455. * Internal
  74456. * @returns if all the contained post processes are ready.
  74457. */
  74458. DepthOfFieldEffect.prototype._isReady = function () {
  74459. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74460. if (!this._effects[effectIndex].isReady()) {
  74461. return false;
  74462. }
  74463. }
  74464. return true;
  74465. };
  74466. return DepthOfFieldEffect;
  74467. }(BABYLON.PostProcessRenderEffect));
  74468. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74469. })(BABYLON || (BABYLON = {}));
  74470. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74471. var BABYLON;
  74472. (function (BABYLON) {
  74473. /**
  74474. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74475. */
  74476. var BloomMergePostProcess = /** @class */ (function (_super) {
  74477. __extends(BloomMergePostProcess, _super);
  74478. /**
  74479. * Creates a new instance of @see BloomMergePostProcess
  74480. * @param name The name of the effect.
  74481. * @param originalFromInput Post process which's input will be used for the merge.
  74482. * @param blurred Blurred highlights post process which's output will be used.
  74483. * @param weight Weight of the bloom to be added to the original input.
  74484. * @param options The required width/height ratio to downsize to before computing the render pass.
  74485. * @param camera The camera to apply the render pass to.
  74486. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74487. * @param engine The engine which the post process will be applied. (default: current engine)
  74488. * @param reusable If the post process can be reused on the same frame. (default: false)
  74489. * @param textureType Type of textures used when performing the post process. (default: 0)
  74490. * @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)
  74491. */
  74492. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74493. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74494. if (blockCompilation === void 0) { blockCompilation = false; }
  74495. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74496. _this.weight = weight;
  74497. _this.onApplyObservable.add(function (effect) {
  74498. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74499. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74500. effect.setFloat("bloomWeight", _this.weight);
  74501. });
  74502. if (!blockCompilation) {
  74503. _this.updateEffect();
  74504. }
  74505. return _this;
  74506. }
  74507. return BloomMergePostProcess;
  74508. }(BABYLON.PostProcess));
  74509. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74510. })(BABYLON || (BABYLON = {}));
  74511. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74512. var BABYLON;
  74513. (function (BABYLON) {
  74514. /**
  74515. * 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.
  74516. */
  74517. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74518. __extends(ExtractHighlightsPostProcess, _super);
  74519. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74520. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74521. if (blockCompilation === void 0) { blockCompilation = false; }
  74522. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74523. /**
  74524. * The luminance threshold, pixels below this value will be set to black.
  74525. */
  74526. _this.threshold = 0.9;
  74527. /**
  74528. * Internal
  74529. */
  74530. _this._exposure = 1;
  74531. /**
  74532. * Post process which has the input texture to be used when performing highlight extraction
  74533. */
  74534. _this._inputPostProcess = null;
  74535. _this.onApplyObservable.add(function (effect) {
  74536. if (_this._inputPostProcess) {
  74537. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74538. }
  74539. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74540. effect.setFloat('exposure', _this._exposure);
  74541. });
  74542. return _this;
  74543. }
  74544. return ExtractHighlightsPostProcess;
  74545. }(BABYLON.PostProcess));
  74546. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74547. })(BABYLON || (BABYLON = {}));
  74548. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74549. var BABYLON;
  74550. (function (BABYLON) {
  74551. /**
  74552. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74553. */
  74554. var BloomEffect = /** @class */ (function (_super) {
  74555. __extends(BloomEffect, _super);
  74556. /**
  74557. * Creates a new instance of @see BloomEffect
  74558. * @param scene The scene the effect belongs to.
  74559. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74560. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74561. * @param bloomWeight The the strength of bloom.
  74562. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74563. * @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)
  74564. */
  74565. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74566. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74567. if (blockCompilation === void 0) { blockCompilation = false; }
  74568. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74569. return _this._effects;
  74570. }, true) || this;
  74571. _this.bloomScale = bloomScale;
  74572. /**
  74573. * Internal
  74574. */
  74575. _this._effects = [];
  74576. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74577. _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);
  74578. _this._blurX.alwaysForcePOT = true;
  74579. _this._blurX.autoClear = false;
  74580. _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);
  74581. _this._blurY.alwaysForcePOT = true;
  74582. _this._blurY.autoClear = false;
  74583. _this.kernel = bloomKernel;
  74584. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74585. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74586. _this._merge.autoClear = false;
  74587. _this._effects.push(_this._merge);
  74588. return _this;
  74589. }
  74590. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74591. /**
  74592. * The luminance threshold to find bright areas of the image to bloom.
  74593. */
  74594. get: function () {
  74595. return this._downscale.threshold;
  74596. },
  74597. set: function (value) {
  74598. this._downscale.threshold = value;
  74599. },
  74600. enumerable: true,
  74601. configurable: true
  74602. });
  74603. Object.defineProperty(BloomEffect.prototype, "weight", {
  74604. /**
  74605. * The strength of the bloom.
  74606. */
  74607. get: function () {
  74608. return this._merge.weight;
  74609. },
  74610. set: function (value) {
  74611. this._merge.weight = value;
  74612. },
  74613. enumerable: true,
  74614. configurable: true
  74615. });
  74616. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74617. /**
  74618. * Specifies the size of the bloom blur kernel, relative to the final output size
  74619. */
  74620. get: function () {
  74621. return this._blurX.kernel / this.bloomScale;
  74622. },
  74623. set: function (value) {
  74624. this._blurX.kernel = value * this.bloomScale;
  74625. this._blurY.kernel = value * this.bloomScale;
  74626. },
  74627. enumerable: true,
  74628. configurable: true
  74629. });
  74630. /**
  74631. * Disposes each of the internal effects for a given camera.
  74632. * @param camera The camera to dispose the effect on.
  74633. */
  74634. BloomEffect.prototype.disposeEffects = function (camera) {
  74635. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74636. this._effects[effectIndex].dispose(camera);
  74637. }
  74638. };
  74639. /**
  74640. * Internal
  74641. */
  74642. BloomEffect.prototype._updateEffects = function () {
  74643. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74644. this._effects[effectIndex].updateEffect();
  74645. }
  74646. };
  74647. /**
  74648. * Internal
  74649. * @returns if all the contained post processes are ready.
  74650. */
  74651. BloomEffect.prototype._isReady = function () {
  74652. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74653. if (!this._effects[effectIndex].isReady()) {
  74654. return false;
  74655. }
  74656. }
  74657. return true;
  74658. };
  74659. return BloomEffect;
  74660. }(BABYLON.PostProcessRenderEffect));
  74661. BABYLON.BloomEffect = BloomEffect;
  74662. })(BABYLON || (BABYLON = {}));
  74663. //# sourceMappingURL=babylon.bloomEffect.js.map
  74664. var BABYLON;
  74665. (function (BABYLON) {
  74666. /**
  74667. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74668. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74669. */
  74670. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74671. __extends(DefaultRenderingPipeline, _super);
  74672. /**
  74673. * @constructor
  74674. * @param {string} name - The rendering pipeline name
  74675. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74676. * @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)
  74677. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74678. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74679. */
  74680. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74681. if (automaticBuild === void 0) { automaticBuild = true; }
  74682. var _this = _super.call(this, scene.getEngine(), name) || this;
  74683. _this._originalCameras = [];
  74684. /**
  74685. * ID of the sharpen post process,
  74686. */
  74687. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74688. /**
  74689. * ID of the image processing post process;
  74690. */
  74691. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74692. /**
  74693. * ID of the Fast Approximate Anti-Aliasing post process;
  74694. */
  74695. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74696. /**
  74697. * ID of the chromatic aberration post process,
  74698. */
  74699. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74700. /**
  74701. * ID of the grain post process
  74702. */
  74703. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74704. /**
  74705. * Animations which can be used to tweak settings over a period of time
  74706. */
  74707. _this.animations = [];
  74708. _this._imageProcessingConfigurationObserver = null;
  74709. // Values
  74710. _this._sharpenEnabled = false;
  74711. _this._bloomEnabled = false;
  74712. _this._depthOfFieldEnabled = false;
  74713. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74714. _this._fxaaEnabled = false;
  74715. _this._imageProcessingEnabled = true;
  74716. _this._bloomScale = 0.5;
  74717. _this._chromaticAberrationEnabled = false;
  74718. _this._grainEnabled = false;
  74719. _this._buildAllowed = true;
  74720. _this._resizeObserver = null;
  74721. _this._hardwareScaleLevel = 1.0;
  74722. _this._bloomKernel = 64;
  74723. /**
  74724. * Specifies the weight of the bloom in the final rendering
  74725. */
  74726. _this._bloomWeight = 0.15;
  74727. /**
  74728. * Specifies the luma threshold for the area that will be blurred by the bloom
  74729. */
  74730. _this._bloomThreshold = 0.9;
  74731. _this._samples = 1;
  74732. _this._hasCleared = false;
  74733. _this._prevPostProcess = null;
  74734. _this._prevPrevPostProcess = null;
  74735. _this._cameras = cameras || [];
  74736. _this._originalCameras = _this._cameras.slice();
  74737. _this._buildAllowed = automaticBuild;
  74738. // Initialize
  74739. _this._scene = scene;
  74740. var caps = _this._scene.getEngine().getCaps();
  74741. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74742. // Misc
  74743. if (_this._hdr) {
  74744. if (caps.textureHalfFloatRender) {
  74745. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74746. }
  74747. else if (caps.textureFloatRender) {
  74748. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74749. }
  74750. }
  74751. else {
  74752. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74753. }
  74754. // Attach
  74755. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74756. var engine = _this._scene.getEngine();
  74757. // Create post processes before hand so they can be modified before enabled.
  74758. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74759. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74760. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74761. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74762. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74763. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74764. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74765. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74766. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74767. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74768. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74769. _this.bloomKernel = _this.bloomKernel;
  74770. });
  74771. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74772. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74773. });
  74774. _this._buildPipeline();
  74775. return _this;
  74776. }
  74777. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74778. get: function () {
  74779. return this._sharpenEnabled;
  74780. },
  74781. /**
  74782. * Enable or disable the sharpen process from the pipeline
  74783. */
  74784. set: function (enabled) {
  74785. if (this._sharpenEnabled === enabled) {
  74786. return;
  74787. }
  74788. this._sharpenEnabled = enabled;
  74789. this._buildPipeline();
  74790. },
  74791. enumerable: true,
  74792. configurable: true
  74793. });
  74794. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74795. /**
  74796. * Specifies the size of the bloom blur kernel, relative to the final output size
  74797. */
  74798. get: function () {
  74799. return this._bloomKernel;
  74800. },
  74801. set: function (value) {
  74802. this._bloomKernel = value;
  74803. this.bloom.kernel = value / this._hardwareScaleLevel;
  74804. },
  74805. enumerable: true,
  74806. configurable: true
  74807. });
  74808. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74809. get: function () {
  74810. return this._bloomWeight;
  74811. },
  74812. /**
  74813. * The strength of the bloom.
  74814. */
  74815. set: function (value) {
  74816. if (this._bloomWeight === value) {
  74817. return;
  74818. }
  74819. this.bloom.weight = value;
  74820. this._bloomWeight = value;
  74821. },
  74822. enumerable: true,
  74823. configurable: true
  74824. });
  74825. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74826. get: function () {
  74827. return this._bloomThreshold;
  74828. },
  74829. /**
  74830. * The strength of the bloom.
  74831. */
  74832. set: function (value) {
  74833. if (this._bloomThreshold === value) {
  74834. return;
  74835. }
  74836. this.bloom.threshold = value;
  74837. this._bloomThreshold = value;
  74838. },
  74839. enumerable: true,
  74840. configurable: true
  74841. });
  74842. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74843. get: function () {
  74844. return this._bloomScale;
  74845. },
  74846. /**
  74847. * The scale of the bloom, lower value will provide better performance.
  74848. */
  74849. set: function (value) {
  74850. if (this._bloomScale === value) {
  74851. return;
  74852. }
  74853. this._bloomScale = value;
  74854. // recreate bloom and dispose old as this setting is not dynamic
  74855. this._rebuildBloom();
  74856. this._buildPipeline();
  74857. },
  74858. enumerable: true,
  74859. configurable: true
  74860. });
  74861. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74862. get: function () {
  74863. return this._bloomEnabled;
  74864. },
  74865. /**
  74866. * Enable or disable the bloom from the pipeline
  74867. */
  74868. set: function (enabled) {
  74869. if (this._bloomEnabled === enabled) {
  74870. return;
  74871. }
  74872. this._bloomEnabled = enabled;
  74873. this._buildPipeline();
  74874. },
  74875. enumerable: true,
  74876. configurable: true
  74877. });
  74878. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74879. // recreate bloom and dispose old as this setting is not dynamic
  74880. var oldBloom = this.bloom;
  74881. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74882. this.bloom.threshold = oldBloom.threshold;
  74883. for (var i = 0; i < this._cameras.length; i++) {
  74884. oldBloom.disposeEffects(this._cameras[i]);
  74885. }
  74886. };
  74887. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74888. /**
  74889. * If the depth of field is enabled.
  74890. */
  74891. get: function () {
  74892. return this._depthOfFieldEnabled;
  74893. },
  74894. set: function (enabled) {
  74895. if (this._depthOfFieldEnabled === enabled) {
  74896. return;
  74897. }
  74898. this._depthOfFieldEnabled = enabled;
  74899. this._buildPipeline();
  74900. },
  74901. enumerable: true,
  74902. configurable: true
  74903. });
  74904. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74905. /**
  74906. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74907. */
  74908. get: function () {
  74909. return this._depthOfFieldBlurLevel;
  74910. },
  74911. set: function (value) {
  74912. if (this._depthOfFieldBlurLevel === value) {
  74913. return;
  74914. }
  74915. this._depthOfFieldBlurLevel = value;
  74916. // recreate dof and dispose old as this setting is not dynamic
  74917. var oldDof = this.depthOfField;
  74918. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74919. this.depthOfField.focalLength = oldDof.focalLength;
  74920. this.depthOfField.focusDistance = oldDof.focusDistance;
  74921. this.depthOfField.fStop = oldDof.fStop;
  74922. this.depthOfField.lensSize = oldDof.lensSize;
  74923. for (var i = 0; i < this._cameras.length; i++) {
  74924. oldDof.disposeEffects(this._cameras[i]);
  74925. }
  74926. this._buildPipeline();
  74927. },
  74928. enumerable: true,
  74929. configurable: true
  74930. });
  74931. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74932. get: function () {
  74933. return this._fxaaEnabled;
  74934. },
  74935. /**
  74936. * If the anti aliasing is enabled.
  74937. */
  74938. set: function (enabled) {
  74939. if (this._fxaaEnabled === enabled) {
  74940. return;
  74941. }
  74942. this._fxaaEnabled = enabled;
  74943. this._buildPipeline();
  74944. },
  74945. enumerable: true,
  74946. configurable: true
  74947. });
  74948. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74949. get: function () {
  74950. return this._samples;
  74951. },
  74952. /**
  74953. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74954. */
  74955. set: function (sampleCount) {
  74956. if (this._samples === sampleCount) {
  74957. return;
  74958. }
  74959. this._samples = sampleCount;
  74960. this._buildPipeline();
  74961. },
  74962. enumerable: true,
  74963. configurable: true
  74964. });
  74965. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74966. get: function () {
  74967. return this._imageProcessingEnabled;
  74968. },
  74969. /**
  74970. * If image processing is enabled.
  74971. */
  74972. set: function (enabled) {
  74973. if (this._imageProcessingEnabled === enabled) {
  74974. return;
  74975. }
  74976. this._imageProcessingEnabled = enabled;
  74977. this._buildPipeline();
  74978. },
  74979. enumerable: true,
  74980. configurable: true
  74981. });
  74982. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74983. get: function () {
  74984. return this._chromaticAberrationEnabled;
  74985. },
  74986. /**
  74987. * Enable or disable the chromaticAberration process from the pipeline
  74988. */
  74989. set: function (enabled) {
  74990. if (this._chromaticAberrationEnabled === enabled) {
  74991. return;
  74992. }
  74993. this._chromaticAberrationEnabled = enabled;
  74994. this._buildPipeline();
  74995. },
  74996. enumerable: true,
  74997. configurable: true
  74998. });
  74999. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75000. get: function () {
  75001. return this._grainEnabled;
  75002. },
  75003. /**
  75004. * Enable or disable the grain process from the pipeline
  75005. */
  75006. set: function (enabled) {
  75007. if (this._grainEnabled === enabled) {
  75008. return;
  75009. }
  75010. this._grainEnabled = enabled;
  75011. this._buildPipeline();
  75012. },
  75013. enumerable: true,
  75014. configurable: true
  75015. });
  75016. /**
  75017. * Force the compilation of the entire pipeline.
  75018. */
  75019. DefaultRenderingPipeline.prototype.prepare = function () {
  75020. var previousState = this._buildAllowed;
  75021. this._buildAllowed = true;
  75022. this._buildPipeline();
  75023. this._buildAllowed = previousState;
  75024. };
  75025. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75026. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75027. if (this._hasCleared) {
  75028. postProcess.autoClear = false;
  75029. }
  75030. else {
  75031. postProcess.autoClear = true;
  75032. this._scene.autoClear = false;
  75033. this._hasCleared = true;
  75034. }
  75035. if (!skipTextureSharing) {
  75036. if (this._prevPrevPostProcess) {
  75037. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75038. }
  75039. else {
  75040. postProcess.useOwnOutput();
  75041. }
  75042. if (this._prevPostProcess) {
  75043. this._prevPrevPostProcess = this._prevPostProcess;
  75044. }
  75045. this._prevPostProcess = postProcess;
  75046. }
  75047. };
  75048. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75049. var _this = this;
  75050. if (!this._buildAllowed) {
  75051. return;
  75052. }
  75053. this._scene.autoClear = true;
  75054. var engine = this._scene.getEngine();
  75055. this._disposePostProcesses();
  75056. if (this._cameras !== null) {
  75057. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75058. // get back cameras to be used to reattach pipeline
  75059. this._cameras = this._originalCameras.slice();
  75060. }
  75061. this._reset();
  75062. this._prevPostProcess = null;
  75063. this._prevPrevPostProcess = null;
  75064. this._hasCleared = false;
  75065. if (this.depthOfFieldEnabled) {
  75066. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75067. this.depthOfField.depthTexture = depthTexture;
  75068. if (!this.depthOfField._isReady()) {
  75069. this.depthOfField._updateEffects();
  75070. }
  75071. this.addEffect(this.depthOfField);
  75072. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75073. }
  75074. if (this.bloomEnabled) {
  75075. if (!this.bloom._isReady()) {
  75076. this.bloom._updateEffects();
  75077. }
  75078. this.addEffect(this.bloom);
  75079. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75080. }
  75081. if (this._imageProcessingEnabled) {
  75082. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75083. if (this._hdr) {
  75084. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75085. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75086. }
  75087. else {
  75088. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75089. }
  75090. }
  75091. if (this.sharpenEnabled) {
  75092. if (!this.sharpen.isReady()) {
  75093. this.sharpen.updateEffect();
  75094. }
  75095. this.addEffect(this._sharpenEffect);
  75096. this._setAutoClearAndTextureSharing(this.sharpen);
  75097. }
  75098. if (this.grainEnabled) {
  75099. if (!this.grain.isReady()) {
  75100. this.grain.updateEffect();
  75101. }
  75102. this.addEffect(this._grainEffect);
  75103. this._setAutoClearAndTextureSharing(this.grain);
  75104. }
  75105. if (this.chromaticAberrationEnabled) {
  75106. if (!this.chromaticAberration.isReady()) {
  75107. this.chromaticAberration.updateEffect();
  75108. }
  75109. this.addEffect(this._chromaticAberrationEffect);
  75110. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75111. }
  75112. if (this.fxaaEnabled) {
  75113. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75114. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75115. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75116. }
  75117. if (this._cameras !== null) {
  75118. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75119. }
  75120. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75121. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75122. }
  75123. };
  75124. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75125. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75126. for (var i = 0; i < this._cameras.length; i++) {
  75127. var camera = this._cameras[i];
  75128. if (this.imageProcessing) {
  75129. this.imageProcessing.dispose(camera);
  75130. }
  75131. if (this.fxaa) {
  75132. this.fxaa.dispose(camera);
  75133. }
  75134. // These are created in the constructor and should not be disposed on every pipeline change
  75135. if (disposeNonRecreated) {
  75136. if (this.sharpen) {
  75137. this.sharpen.dispose(camera);
  75138. }
  75139. if (this.depthOfField) {
  75140. this.depthOfField.disposeEffects(camera);
  75141. }
  75142. if (this.bloom) {
  75143. this.bloom.disposeEffects(camera);
  75144. }
  75145. if (this.chromaticAberration) {
  75146. this.chromaticAberration.dispose(camera);
  75147. }
  75148. if (this.grain) {
  75149. this.grain.dispose(camera);
  75150. }
  75151. }
  75152. }
  75153. this.imageProcessing = null;
  75154. this.fxaa = null;
  75155. if (disposeNonRecreated) {
  75156. this.sharpen = null;
  75157. this._sharpenEffect = null;
  75158. this.depthOfField = null;
  75159. this.bloom = null;
  75160. this.chromaticAberration = null;
  75161. this._chromaticAberrationEffect = null;
  75162. this.grain = null;
  75163. this._grainEffect = null;
  75164. }
  75165. };
  75166. /**
  75167. * Dispose of the pipeline and stop all post processes
  75168. */
  75169. DefaultRenderingPipeline.prototype.dispose = function () {
  75170. this._disposePostProcesses(true);
  75171. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75172. this._scene.autoClear = true;
  75173. if (this._resizeObserver) {
  75174. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75175. this._resizeObserver = null;
  75176. }
  75177. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75178. _super.prototype.dispose.call(this);
  75179. };
  75180. /**
  75181. * Serialize the rendering pipeline (Used when exporting)
  75182. * @returns the serialized object
  75183. */
  75184. DefaultRenderingPipeline.prototype.serialize = function () {
  75185. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75186. serializationObject.customType = "DefaultRenderingPipeline";
  75187. return serializationObject;
  75188. };
  75189. /**
  75190. * Parse the serialized pipeline
  75191. * @param source Source pipeline.
  75192. * @param scene The scene to load the pipeline to.
  75193. * @param rootUrl The URL of the serialized pipeline.
  75194. * @returns An instantiated pipeline from the serialized object.
  75195. */
  75196. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75197. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75198. };
  75199. __decorate([
  75200. BABYLON.serialize()
  75201. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75202. __decorate([
  75203. BABYLON.serialize()
  75204. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75205. __decorate([
  75206. BABYLON.serialize()
  75207. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75208. __decorate([
  75209. BABYLON.serialize()
  75210. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75211. __decorate([
  75212. BABYLON.serialize()
  75213. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75214. __decorate([
  75215. BABYLON.serialize()
  75216. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75217. __decorate([
  75218. BABYLON.serialize()
  75219. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75220. __decorate([
  75221. BABYLON.serialize()
  75222. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75223. __decorate([
  75224. BABYLON.serialize()
  75225. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75226. __decorate([
  75227. BABYLON.serialize()
  75228. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75229. __decorate([
  75230. BABYLON.serialize()
  75231. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75232. __decorate([
  75233. BABYLON.serialize()
  75234. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75235. __decorate([
  75236. BABYLON.serialize()
  75237. ], DefaultRenderingPipeline.prototype, "samples", null);
  75238. __decorate([
  75239. BABYLON.serialize()
  75240. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75241. __decorate([
  75242. BABYLON.serialize()
  75243. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75244. __decorate([
  75245. BABYLON.serialize()
  75246. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75247. return DefaultRenderingPipeline;
  75248. }(BABYLON.PostProcessRenderPipeline));
  75249. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75250. })(BABYLON || (BABYLON = {}));
  75251. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75252. var BABYLON;
  75253. (function (BABYLON) {
  75254. /**
  75255. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75256. */
  75257. var GeometryBufferRenderer = /** @class */ (function () {
  75258. /**
  75259. * Creates a new G Buffer for the scene
  75260. * @param scene The scene the buffer belongs to
  75261. * @param ratio How big is the buffer related to the main canvas.
  75262. */
  75263. function GeometryBufferRenderer(scene, ratio) {
  75264. if (ratio === void 0) { ratio = 1; }
  75265. this._enablePosition = false;
  75266. this._scene = scene;
  75267. this._ratio = ratio;
  75268. // Render target
  75269. this._createRenderTargets();
  75270. }
  75271. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75272. /**
  75273. * Set the render list (meshes to be rendered) used in the G buffer.
  75274. */
  75275. set: function (meshes) {
  75276. this._multiRenderTarget.renderList = meshes;
  75277. },
  75278. enumerable: true,
  75279. configurable: true
  75280. });
  75281. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75282. /**
  75283. * Gets wether or not G buffer are supported by the running hardware.
  75284. * This requires draw buffer supports
  75285. */
  75286. get: function () {
  75287. return this._multiRenderTarget.isSupported;
  75288. },
  75289. enumerable: true,
  75290. configurable: true
  75291. });
  75292. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75293. /**
  75294. * Gets wether or not position are enabled for the G buffer.
  75295. */
  75296. get: function () {
  75297. return this._enablePosition;
  75298. },
  75299. /**
  75300. * Sets wether or not position are enabled for the G buffer.
  75301. */
  75302. set: function (enable) {
  75303. this._enablePosition = enable;
  75304. this.dispose();
  75305. this._createRenderTargets();
  75306. },
  75307. enumerable: true,
  75308. configurable: true
  75309. });
  75310. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75311. /**
  75312. * Gets the scene associated with the buffer.
  75313. */
  75314. get: function () {
  75315. return this._scene;
  75316. },
  75317. enumerable: true,
  75318. configurable: true
  75319. });
  75320. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75321. /**
  75322. * Gets the ratio used by the buffer during its creation.
  75323. * How big is the buffer related to the main canvas.
  75324. */
  75325. get: function () {
  75326. return this._ratio;
  75327. },
  75328. enumerable: true,
  75329. configurable: true
  75330. });
  75331. /**
  75332. * Checks wether everything is ready to render a submesh to the G buffer.
  75333. * @param subMesh the submesh to check readiness for
  75334. * @param useInstances is the mesh drawn using instance or not
  75335. * @returns true if ready otherwise false
  75336. */
  75337. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75338. var material = subMesh.getMaterial();
  75339. if (material && material.disableDepthWrite) {
  75340. return false;
  75341. }
  75342. var defines = [];
  75343. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75344. var mesh = subMesh.getMesh();
  75345. // Alpha test
  75346. if (material && material.needAlphaTesting()) {
  75347. defines.push("#define ALPHATEST");
  75348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75349. attribs.push(BABYLON.VertexBuffer.UVKind);
  75350. defines.push("#define UV1");
  75351. }
  75352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75354. defines.push("#define UV2");
  75355. }
  75356. }
  75357. // Buffers
  75358. if (this._enablePosition) {
  75359. defines.push("#define POSITION");
  75360. }
  75361. // Bones
  75362. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75365. if (mesh.numBoneInfluencers > 4) {
  75366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75368. }
  75369. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75370. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75371. }
  75372. else {
  75373. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75374. }
  75375. // Instances
  75376. if (useInstances) {
  75377. defines.push("#define INSTANCES");
  75378. attribs.push("world0");
  75379. attribs.push("world1");
  75380. attribs.push("world2");
  75381. attribs.push("world3");
  75382. }
  75383. // Get correct effect
  75384. var join = defines.join("\n");
  75385. if (this._cachedDefines !== join) {
  75386. this._cachedDefines = join;
  75387. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75388. }
  75389. return this._effect.isReady();
  75390. };
  75391. /**
  75392. * Gets the current underlying G Buffer.
  75393. * @returns the buffer
  75394. */
  75395. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75396. return this._multiRenderTarget;
  75397. };
  75398. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75399. /**
  75400. * Gets the number of samples used to render the buffer (anti aliasing).
  75401. */
  75402. get: function () {
  75403. return this._multiRenderTarget.samples;
  75404. },
  75405. /**
  75406. * Sets the number of samples used to render the buffer (anti aliasing).
  75407. */
  75408. set: function (value) {
  75409. this._multiRenderTarget.samples = value;
  75410. },
  75411. enumerable: true,
  75412. configurable: true
  75413. });
  75414. /**
  75415. * Disposes the renderer and frees up associated resources.
  75416. */
  75417. GeometryBufferRenderer.prototype.dispose = function () {
  75418. this.getGBuffer().dispose();
  75419. };
  75420. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75421. var _this = this;
  75422. var engine = this._scene.getEngine();
  75423. var count = this._enablePosition ? 3 : 2;
  75424. 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 });
  75425. if (!this.isSupported) {
  75426. return;
  75427. }
  75428. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75429. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75430. this._multiRenderTarget.refreshRate = 1;
  75431. this._multiRenderTarget.renderParticles = false;
  75432. this._multiRenderTarget.renderList = null;
  75433. // set default depth value to 1.0 (far away)
  75434. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75435. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75436. });
  75437. // Custom render function
  75438. var renderSubMesh = function (subMesh) {
  75439. var mesh = subMesh.getRenderingMesh();
  75440. var scene = _this._scene;
  75441. var engine = scene.getEngine();
  75442. var material = subMesh.getMaterial();
  75443. if (!material) {
  75444. return;
  75445. }
  75446. // Culling
  75447. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75448. // Managing instances
  75449. var batch = mesh._getInstancesRenderList(subMesh._id);
  75450. if (batch.mustReturn) {
  75451. return;
  75452. }
  75453. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75454. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75455. engine.enableEffect(_this._effect);
  75456. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75457. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75458. _this._effect.setMatrix("view", scene.getViewMatrix());
  75459. // Alpha test
  75460. if (material && material.needAlphaTesting()) {
  75461. var alphaTexture = material.getAlphaTestTexture();
  75462. if (alphaTexture) {
  75463. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75464. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75465. }
  75466. }
  75467. // Bones
  75468. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75469. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75470. }
  75471. // Draw
  75472. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75473. }
  75474. };
  75475. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75476. var index;
  75477. if (depthOnlySubMeshes.length) {
  75478. engine.setColorWrite(false);
  75479. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75480. renderSubMesh(depthOnlySubMeshes.data[index]);
  75481. }
  75482. engine.setColorWrite(true);
  75483. }
  75484. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75485. renderSubMesh(opaqueSubMeshes.data[index]);
  75486. }
  75487. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75488. renderSubMesh(alphaTestSubMeshes.data[index]);
  75489. }
  75490. };
  75491. };
  75492. return GeometryBufferRenderer;
  75493. }());
  75494. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75495. })(BABYLON || (BABYLON = {}));
  75496. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75497. var BABYLON;
  75498. (function (BABYLON) {
  75499. var RefractionPostProcess = /** @class */ (function (_super) {
  75500. __extends(RefractionPostProcess, _super);
  75501. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75502. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75503. _this.color = color;
  75504. _this.depth = depth;
  75505. _this.colorLevel = colorLevel;
  75506. _this._ownRefractionTexture = true;
  75507. _this.onActivateObservable.add(function (cam) {
  75508. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75509. });
  75510. _this.onApplyObservable.add(function (effect) {
  75511. effect.setColor3("baseColor", _this.color);
  75512. effect.setFloat("depth", _this.depth);
  75513. effect.setFloat("colorLevel", _this.colorLevel);
  75514. effect.setTexture("refractionSampler", _this._refTexture);
  75515. });
  75516. return _this;
  75517. }
  75518. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75519. /**
  75520. * Gets or sets the refraction texture
  75521. * Please note that you are responsible for disposing the texture if you set it manually
  75522. */
  75523. get: function () {
  75524. return this._refTexture;
  75525. },
  75526. set: function (value) {
  75527. if (this._refTexture && this._ownRefractionTexture) {
  75528. this._refTexture.dispose();
  75529. }
  75530. this._refTexture = value;
  75531. this._ownRefractionTexture = false;
  75532. },
  75533. enumerable: true,
  75534. configurable: true
  75535. });
  75536. // Methods
  75537. RefractionPostProcess.prototype.dispose = function (camera) {
  75538. if (this._refTexture && this._ownRefractionTexture) {
  75539. this._refTexture.dispose();
  75540. this._refTexture = null;
  75541. }
  75542. _super.prototype.dispose.call(this, camera);
  75543. };
  75544. return RefractionPostProcess;
  75545. }(BABYLON.PostProcess));
  75546. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75547. })(BABYLON || (BABYLON = {}));
  75548. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75549. var BABYLON;
  75550. (function (BABYLON) {
  75551. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75552. __extends(BlackAndWhitePostProcess, _super);
  75553. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75554. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75555. _this.degree = 1;
  75556. _this.onApplyObservable.add(function (effect) {
  75557. effect.setFloat("degree", _this.degree);
  75558. });
  75559. return _this;
  75560. }
  75561. return BlackAndWhitePostProcess;
  75562. }(BABYLON.PostProcess));
  75563. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75564. })(BABYLON || (BABYLON = {}));
  75565. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75566. var BABYLON;
  75567. (function (BABYLON) {
  75568. /**
  75569. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75570. * input texture to perform effects such as edge detection or sharpening
  75571. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75572. */
  75573. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75574. __extends(ConvolutionPostProcess, _super);
  75575. /**
  75576. * Creates a new instance ConvolutionPostProcess
  75577. * @param name The name of the effect.
  75578. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75579. * @param options The required width/height ratio to downsize to before computing the render pass.
  75580. * @param camera The camera to apply the render pass to.
  75581. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75582. * @param engine The engine which the post process will be applied. (default: current engine)
  75583. * @param reusable If the post process can be reused on the same frame. (default: false)
  75584. * @param textureType Type of textures used when performing the post process. (default: 0)
  75585. */
  75586. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75587. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75588. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75589. _this.kernel = kernel;
  75590. _this.onApply = function (effect) {
  75591. effect.setFloat2("screenSize", _this.width, _this.height);
  75592. effect.setArray("kernel", _this.kernel);
  75593. };
  75594. return _this;
  75595. }
  75596. // Statics
  75597. /**
  75598. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75599. */
  75600. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75601. /**
  75602. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75603. */
  75604. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75605. /**
  75606. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75607. */
  75608. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75609. /**
  75610. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75611. */
  75612. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75613. /**
  75614. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75615. */
  75616. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75617. /**
  75618. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75619. */
  75620. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75621. return ConvolutionPostProcess;
  75622. }(BABYLON.PostProcess));
  75623. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75624. })(BABYLON || (BABYLON = {}));
  75625. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75626. var BABYLON;
  75627. (function (BABYLON) {
  75628. var FilterPostProcess = /** @class */ (function (_super) {
  75629. __extends(FilterPostProcess, _super);
  75630. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75631. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75632. _this.kernelMatrix = kernelMatrix;
  75633. _this.onApply = function (effect) {
  75634. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75635. };
  75636. return _this;
  75637. }
  75638. return FilterPostProcess;
  75639. }(BABYLON.PostProcess));
  75640. BABYLON.FilterPostProcess = FilterPostProcess;
  75641. })(BABYLON || (BABYLON = {}));
  75642. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75643. var BABYLON;
  75644. (function (BABYLON) {
  75645. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75646. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75647. __extends(VolumetricLightScatteringPostProcess, _super);
  75648. /**
  75649. * @constructor
  75650. * @param {string} name - The post-process name
  75651. * @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)
  75652. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75653. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75654. * @param {number} samples - The post-process quality, default 100
  75655. * @param {number} samplingMode - The post-process filtering mode
  75656. * @param {BABYLON.Engine} engine - The babylon engine
  75657. * @param {boolean} reusable - If the post-process is reusable
  75658. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75659. */
  75660. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75661. if (samples === void 0) { samples = 100; }
  75662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75663. 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;
  75664. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75665. /**
  75666. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75667. */
  75668. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75669. /**
  75670. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75671. */
  75672. _this.useCustomMeshPosition = false;
  75673. /**
  75674. * If the post-process should inverse the light scattering direction
  75675. */
  75676. _this.invert = true;
  75677. /**
  75678. * Array containing the excluded meshes not rendered in the internal pass
  75679. */
  75680. _this.excludedMeshes = new Array();
  75681. /**
  75682. * Controls the overall intensity of the post-process
  75683. */
  75684. _this.exposure = 0.3;
  75685. /**
  75686. * Dissipates each sample's contribution in range [0, 1]
  75687. */
  75688. _this.decay = 0.96815;
  75689. /**
  75690. * Controls the overall intensity of each sample
  75691. */
  75692. _this.weight = 0.58767;
  75693. /**
  75694. * Controls the density of each sample
  75695. */
  75696. _this.density = 0.926;
  75697. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75698. engine = scene.getEngine();
  75699. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75700. // Configure mesh
  75701. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75702. // Configure
  75703. _this._createPass(scene, ratio.passRatio || ratio);
  75704. _this.onActivate = function (camera) {
  75705. if (!_this.isSupported) {
  75706. _this.dispose(camera);
  75707. }
  75708. _this.onActivate = null;
  75709. };
  75710. _this.onApplyObservable.add(function (effect) {
  75711. _this._updateMeshScreenCoordinates(scene);
  75712. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75713. effect.setFloat("exposure", _this.exposure);
  75714. effect.setFloat("decay", _this.decay);
  75715. effect.setFloat("weight", _this.weight);
  75716. effect.setFloat("density", _this.density);
  75717. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75718. });
  75719. return _this;
  75720. }
  75721. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75722. get: function () {
  75723. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75724. return false;
  75725. },
  75726. set: function (useDiffuseColor) {
  75727. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75728. },
  75729. enumerable: true,
  75730. configurable: true
  75731. });
  75732. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75733. return "VolumetricLightScatteringPostProcess";
  75734. };
  75735. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75736. var mesh = subMesh.getMesh();
  75737. // Render this.mesh as default
  75738. if (mesh === this.mesh && mesh.material) {
  75739. return mesh.material.isReady(mesh);
  75740. }
  75741. var defines = [];
  75742. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75743. var material = subMesh.getMaterial();
  75744. // Alpha test
  75745. if (material) {
  75746. if (material.needAlphaTesting()) {
  75747. defines.push("#define ALPHATEST");
  75748. }
  75749. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75750. attribs.push(BABYLON.VertexBuffer.UVKind);
  75751. defines.push("#define UV1");
  75752. }
  75753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75754. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75755. defines.push("#define UV2");
  75756. }
  75757. }
  75758. // Bones
  75759. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75760. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75761. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75762. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75763. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75764. }
  75765. else {
  75766. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75767. }
  75768. // Instances
  75769. if (useInstances) {
  75770. defines.push("#define INSTANCES");
  75771. attribs.push("world0");
  75772. attribs.push("world1");
  75773. attribs.push("world2");
  75774. attribs.push("world3");
  75775. }
  75776. // Get correct effect
  75777. var join = defines.join("\n");
  75778. if (this._cachedDefines !== join) {
  75779. this._cachedDefines = join;
  75780. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75781. }
  75782. return this._volumetricLightScatteringPass.isReady();
  75783. };
  75784. /**
  75785. * Sets the new light position for light scattering effect
  75786. * @param {BABYLON.Vector3} The new custom light position
  75787. */
  75788. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75789. this.customMeshPosition = position;
  75790. };
  75791. /**
  75792. * Returns the light position for light scattering effect
  75793. * @return {BABYLON.Vector3} The custom light position
  75794. */
  75795. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75796. return this.customMeshPosition;
  75797. };
  75798. /**
  75799. * Disposes the internal assets and detaches the post-process from the camera
  75800. */
  75801. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75802. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75803. if (rttIndex !== -1) {
  75804. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75805. }
  75806. this._volumetricLightScatteringRTT.dispose();
  75807. _super.prototype.dispose.call(this, camera);
  75808. };
  75809. /**
  75810. * Returns the render target texture used by the post-process
  75811. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75812. */
  75813. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75814. return this._volumetricLightScatteringRTT;
  75815. };
  75816. // Private methods
  75817. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75818. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75819. return true;
  75820. }
  75821. return false;
  75822. };
  75823. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75824. var _this = this;
  75825. var engine = scene.getEngine();
  75826. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75827. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75828. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75829. this._volumetricLightScatteringRTT.renderList = null;
  75830. this._volumetricLightScatteringRTT.renderParticles = false;
  75831. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75832. var camera = this.getCamera();
  75833. if (camera) {
  75834. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75835. }
  75836. else {
  75837. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75838. }
  75839. // Custom render function for submeshes
  75840. var renderSubMesh = function (subMesh) {
  75841. var mesh = subMesh.getRenderingMesh();
  75842. if (_this._meshExcluded(mesh)) {
  75843. return;
  75844. }
  75845. var material = subMesh.getMaterial();
  75846. if (!material) {
  75847. return;
  75848. }
  75849. var scene = mesh.getScene();
  75850. var engine = scene.getEngine();
  75851. // Culling
  75852. engine.setState(material.backFaceCulling);
  75853. // Managing instances
  75854. var batch = mesh._getInstancesRenderList(subMesh._id);
  75855. if (batch.mustReturn) {
  75856. return;
  75857. }
  75858. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75859. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75860. var effect = _this._volumetricLightScatteringPass;
  75861. if (mesh === _this.mesh) {
  75862. if (subMesh.effect) {
  75863. effect = subMesh.effect;
  75864. }
  75865. else {
  75866. effect = material.getEffect();
  75867. }
  75868. }
  75869. engine.enableEffect(effect);
  75870. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75871. if (mesh === _this.mesh) {
  75872. material.bind(mesh.getWorldMatrix(), mesh);
  75873. }
  75874. else {
  75875. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75876. // Alpha test
  75877. if (material && material.needAlphaTesting()) {
  75878. var alphaTexture = material.getAlphaTestTexture();
  75879. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75880. if (alphaTexture) {
  75881. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75882. }
  75883. }
  75884. // Bones
  75885. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75886. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75887. }
  75888. }
  75889. // Draw
  75890. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75891. }
  75892. };
  75893. // Render target texture callbacks
  75894. var savedSceneClearColor;
  75895. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75896. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75897. savedSceneClearColor = scene.clearColor;
  75898. scene.clearColor = sceneClearColor;
  75899. });
  75900. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75901. scene.clearColor = savedSceneClearColor;
  75902. });
  75903. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75904. var engine = scene.getEngine();
  75905. var index;
  75906. if (depthOnlySubMeshes.length) {
  75907. engine.setColorWrite(false);
  75908. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75909. renderSubMesh(depthOnlySubMeshes.data[index]);
  75910. }
  75911. engine.setColorWrite(true);
  75912. }
  75913. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75914. renderSubMesh(opaqueSubMeshes.data[index]);
  75915. }
  75916. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75917. renderSubMesh(alphaTestSubMeshes.data[index]);
  75918. }
  75919. if (transparentSubMeshes.length) {
  75920. // Sort sub meshes
  75921. for (index = 0; index < transparentSubMeshes.length; index++) {
  75922. var submesh = transparentSubMeshes.data[index];
  75923. var boundingInfo = submesh.getBoundingInfo();
  75924. if (boundingInfo && scene.activeCamera) {
  75925. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75926. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75927. }
  75928. }
  75929. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75930. sortedArray.sort(function (a, b) {
  75931. // Alpha index first
  75932. if (a._alphaIndex > b._alphaIndex) {
  75933. return 1;
  75934. }
  75935. if (a._alphaIndex < b._alphaIndex) {
  75936. return -1;
  75937. }
  75938. // Then distance to camera
  75939. if (a._distanceToCamera < b._distanceToCamera) {
  75940. return 1;
  75941. }
  75942. if (a._distanceToCamera > b._distanceToCamera) {
  75943. return -1;
  75944. }
  75945. return 0;
  75946. });
  75947. // Render sub meshes
  75948. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75949. for (index = 0; index < sortedArray.length; index++) {
  75950. renderSubMesh(sortedArray[index]);
  75951. }
  75952. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75953. }
  75954. };
  75955. };
  75956. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75957. var transform = scene.getTransformMatrix();
  75958. var meshPosition;
  75959. if (this.useCustomMeshPosition) {
  75960. meshPosition = this.customMeshPosition;
  75961. }
  75962. else if (this.attachedNode) {
  75963. meshPosition = this.attachedNode.position;
  75964. }
  75965. else {
  75966. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75967. }
  75968. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75969. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75970. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75971. if (this.invert)
  75972. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75973. };
  75974. // Static methods
  75975. /**
  75976. * Creates a default mesh for the Volumeric Light Scattering post-process
  75977. * @param {string} The mesh name
  75978. * @param {BABYLON.Scene} The scene where to create the mesh
  75979. * @return {BABYLON.Mesh} the default mesh
  75980. */
  75981. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75982. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75983. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75984. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75985. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75986. mesh.material = material;
  75987. return mesh;
  75988. };
  75989. __decorate([
  75990. BABYLON.serializeAsVector3()
  75991. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75992. __decorate([
  75993. BABYLON.serialize()
  75994. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75995. __decorate([
  75996. BABYLON.serialize()
  75997. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75998. __decorate([
  75999. BABYLON.serializeAsMeshReference()
  76000. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76001. __decorate([
  76002. BABYLON.serialize()
  76003. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76004. __decorate([
  76005. BABYLON.serialize()
  76006. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76007. __decorate([
  76008. BABYLON.serialize()
  76009. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76010. __decorate([
  76011. BABYLON.serialize()
  76012. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76013. __decorate([
  76014. BABYLON.serialize()
  76015. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76016. return VolumetricLightScatteringPostProcess;
  76017. }(BABYLON.PostProcess));
  76018. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76019. })(BABYLON || (BABYLON = {}));
  76020. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76021. //
  76022. // This post-process allows the modification of rendered colors by using
  76023. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76024. //
  76025. // The object needs to be provided an url to a texture containing the color
  76026. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76027. // Use an image editing software to tweak the LUT to match your needs.
  76028. //
  76029. // For an example of a color LUT, see here:
  76030. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76031. // For explanations on color grading, see here:
  76032. // http://udn.epicgames.com/Three/ColorGrading.html
  76033. //
  76034. var BABYLON;
  76035. (function (BABYLON) {
  76036. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76037. __extends(ColorCorrectionPostProcess, _super);
  76038. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76039. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76040. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76041. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76042. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76043. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76044. _this.onApply = function (effect) {
  76045. effect.setTexture("colorTable", _this._colorTableTexture);
  76046. };
  76047. return _this;
  76048. }
  76049. return ColorCorrectionPostProcess;
  76050. }(BABYLON.PostProcess));
  76051. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76052. })(BABYLON || (BABYLON = {}));
  76053. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76054. var BABYLON;
  76055. (function (BABYLON) {
  76056. /** Defines operator used for tonemapping */
  76057. var TonemappingOperator;
  76058. (function (TonemappingOperator) {
  76059. /** Hable */
  76060. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76061. /** Reinhard */
  76062. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76063. /** HejiDawson */
  76064. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76065. /** Photographic */
  76066. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76067. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76068. ;
  76069. /**
  76070. * Defines a post process to apply tone mapping
  76071. */
  76072. var TonemapPostProcess = /** @class */ (function (_super) {
  76073. __extends(TonemapPostProcess, _super);
  76074. /**
  76075. * Creates a new TonemapPostProcess
  76076. * @param name defines the name of the postprocess
  76077. * @param _operator defines the operator to use
  76078. * @param exposureAdjustment defines the required exposure adjustement
  76079. * @param camera defines the camera to use (can be null)
  76080. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76081. * @param engine defines the hosting engine (can be ignore if camera is set)
  76082. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76083. */
  76084. function TonemapPostProcess(name, _operator,
  76085. /** Defines the required exposure adjustement */
  76086. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76088. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76089. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76090. _this._operator = _operator;
  76091. _this.exposureAdjustment = exposureAdjustment;
  76092. var defines = "#define ";
  76093. if (_this._operator === TonemappingOperator.Hable)
  76094. defines += "HABLE_TONEMAPPING";
  76095. else if (_this._operator === TonemappingOperator.Reinhard)
  76096. defines += "REINHARD_TONEMAPPING";
  76097. else if (_this._operator === TonemappingOperator.HejiDawson)
  76098. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76099. else if (_this._operator === TonemappingOperator.Photographic)
  76100. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76101. //sadly a second call to create the effect.
  76102. _this.updateEffect(defines);
  76103. _this.onApply = function (effect) {
  76104. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76105. };
  76106. return _this;
  76107. }
  76108. return TonemapPostProcess;
  76109. }(BABYLON.PostProcess));
  76110. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76111. })(BABYLON || (BABYLON = {}));
  76112. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76113. var BABYLON;
  76114. (function (BABYLON) {
  76115. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76116. __extends(DisplayPassPostProcess, _super);
  76117. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76118. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76119. }
  76120. return DisplayPassPostProcess;
  76121. }(BABYLON.PostProcess));
  76122. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76123. })(BABYLON || (BABYLON = {}));
  76124. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76125. var BABYLON;
  76126. (function (BABYLON) {
  76127. var HighlightsPostProcess = /** @class */ (function (_super) {
  76128. __extends(HighlightsPostProcess, _super);
  76129. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76130. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76131. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76132. }
  76133. return HighlightsPostProcess;
  76134. }(BABYLON.PostProcess));
  76135. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76136. })(BABYLON || (BABYLON = {}));
  76137. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76138. var BABYLON;
  76139. (function (BABYLON) {
  76140. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76141. __extends(ImageProcessingPostProcess, _super);
  76142. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76143. if (camera === void 0) { camera = null; }
  76144. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76145. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76146. _this._fromLinearSpace = true;
  76147. /**
  76148. * Defines cache preventing GC.
  76149. */
  76150. _this._defines = {
  76151. IMAGEPROCESSING: false,
  76152. VIGNETTE: false,
  76153. VIGNETTEBLENDMODEMULTIPLY: false,
  76154. VIGNETTEBLENDMODEOPAQUE: false,
  76155. TONEMAPPING: false,
  76156. CONTRAST: false,
  76157. COLORCURVES: false,
  76158. COLORGRADING: false,
  76159. COLORGRADING3D: false,
  76160. FROMLINEARSPACE: false,
  76161. SAMPLER3DGREENDEPTH: false,
  76162. SAMPLER3DBGRMAP: false,
  76163. IMAGEPROCESSINGPOSTPROCESS: false,
  76164. EXPOSURE: false,
  76165. };
  76166. // Setup the configuration as forced by the constructor. This would then not force the
  76167. // scene materials output in linear space and let untouched the default forward pass.
  76168. if (imageProcessingConfiguration) {
  76169. imageProcessingConfiguration.applyByPostProcess = true;
  76170. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76171. // This will cause the shader to be compiled
  76172. _this.fromLinearSpace = false;
  76173. }
  76174. // Setup the default processing configuration to the scene.
  76175. else {
  76176. _this._attachImageProcessingConfiguration(null, true);
  76177. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76178. }
  76179. _this.onApply = function (effect) {
  76180. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76181. };
  76182. return _this;
  76183. }
  76184. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76185. /**
  76186. * Gets the image processing configuration used either in this material.
  76187. */
  76188. get: function () {
  76189. return this._imageProcessingConfiguration;
  76190. },
  76191. /**
  76192. * Sets the Default image processing configuration used either in the this material.
  76193. *
  76194. * If sets to null, the scene one is in use.
  76195. */
  76196. set: function (value) {
  76197. this._attachImageProcessingConfiguration(value);
  76198. },
  76199. enumerable: true,
  76200. configurable: true
  76201. });
  76202. /**
  76203. * Attaches a new image processing configuration to the PBR Material.
  76204. * @param configuration
  76205. */
  76206. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76207. var _this = this;
  76208. if (doNotBuild === void 0) { doNotBuild = false; }
  76209. if (configuration === this._imageProcessingConfiguration) {
  76210. return;
  76211. }
  76212. // Detaches observer.
  76213. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76214. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76215. }
  76216. // Pick the scene configuration if needed.
  76217. if (!configuration) {
  76218. var scene = null;
  76219. var engine = this.getEngine();
  76220. var camera = this.getCamera();
  76221. if (camera) {
  76222. scene = camera.getScene();
  76223. }
  76224. else if (engine && engine.scenes) {
  76225. var scenes = engine.scenes;
  76226. scene = scenes[scenes.length - 1];
  76227. }
  76228. else {
  76229. scene = BABYLON.Engine.LastCreatedScene;
  76230. }
  76231. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76232. }
  76233. else {
  76234. this._imageProcessingConfiguration = configuration;
  76235. }
  76236. // Attaches observer.
  76237. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76238. _this._updateParameters();
  76239. });
  76240. // Ensure the effect will be rebuilt.
  76241. if (!doNotBuild) {
  76242. this._updateParameters();
  76243. }
  76244. };
  76245. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76246. /**
  76247. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76248. */
  76249. get: function () {
  76250. return this.imageProcessingConfiguration.colorCurves;
  76251. },
  76252. /**
  76253. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76254. */
  76255. set: function (value) {
  76256. this.imageProcessingConfiguration.colorCurves = value;
  76257. },
  76258. enumerable: true,
  76259. configurable: true
  76260. });
  76261. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76262. /**
  76263. * Gets wether the color curves effect is enabled.
  76264. */
  76265. get: function () {
  76266. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76267. },
  76268. /**
  76269. * Sets wether the color curves effect is enabled.
  76270. */
  76271. set: function (value) {
  76272. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76273. },
  76274. enumerable: true,
  76275. configurable: true
  76276. });
  76277. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76278. /**
  76279. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76280. */
  76281. get: function () {
  76282. return this.imageProcessingConfiguration.colorGradingTexture;
  76283. },
  76284. /**
  76285. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76286. */
  76287. set: function (value) {
  76288. this.imageProcessingConfiguration.colorGradingTexture = value;
  76289. },
  76290. enumerable: true,
  76291. configurable: true
  76292. });
  76293. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76294. /**
  76295. * Gets wether the color grading effect is enabled.
  76296. */
  76297. get: function () {
  76298. return this.imageProcessingConfiguration.colorGradingEnabled;
  76299. },
  76300. /**
  76301. * Gets wether the color grading effect is enabled.
  76302. */
  76303. set: function (value) {
  76304. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76305. },
  76306. enumerable: true,
  76307. configurable: true
  76308. });
  76309. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76310. /**
  76311. * Gets exposure used in the effect.
  76312. */
  76313. get: function () {
  76314. return this.imageProcessingConfiguration.exposure;
  76315. },
  76316. /**
  76317. * Sets exposure used in the effect.
  76318. */
  76319. set: function (value) {
  76320. this.imageProcessingConfiguration.exposure = value;
  76321. },
  76322. enumerable: true,
  76323. configurable: true
  76324. });
  76325. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76326. /**
  76327. * Gets wether tonemapping is enabled or not.
  76328. */
  76329. get: function () {
  76330. return this._imageProcessingConfiguration.toneMappingEnabled;
  76331. },
  76332. /**
  76333. * Sets wether tonemapping is enabled or not
  76334. */
  76335. set: function (value) {
  76336. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76337. },
  76338. enumerable: true,
  76339. configurable: true
  76340. });
  76341. ;
  76342. ;
  76343. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76344. /**
  76345. * Gets contrast used in the effect.
  76346. */
  76347. get: function () {
  76348. return this.imageProcessingConfiguration.contrast;
  76349. },
  76350. /**
  76351. * Sets contrast used in the effect.
  76352. */
  76353. set: function (value) {
  76354. this.imageProcessingConfiguration.contrast = value;
  76355. },
  76356. enumerable: true,
  76357. configurable: true
  76358. });
  76359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76360. /**
  76361. * Gets Vignette stretch size.
  76362. */
  76363. get: function () {
  76364. return this.imageProcessingConfiguration.vignetteStretch;
  76365. },
  76366. /**
  76367. * Sets Vignette stretch size.
  76368. */
  76369. set: function (value) {
  76370. this.imageProcessingConfiguration.vignetteStretch = value;
  76371. },
  76372. enumerable: true,
  76373. configurable: true
  76374. });
  76375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76376. /**
  76377. * Gets Vignette centre X Offset.
  76378. */
  76379. get: function () {
  76380. return this.imageProcessingConfiguration.vignetteCentreX;
  76381. },
  76382. /**
  76383. * Sets Vignette centre X Offset.
  76384. */
  76385. set: function (value) {
  76386. this.imageProcessingConfiguration.vignetteCentreX = value;
  76387. },
  76388. enumerable: true,
  76389. configurable: true
  76390. });
  76391. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76392. /**
  76393. * Gets Vignette centre Y Offset.
  76394. */
  76395. get: function () {
  76396. return this.imageProcessingConfiguration.vignetteCentreY;
  76397. },
  76398. /**
  76399. * Sets Vignette centre Y Offset.
  76400. */
  76401. set: function (value) {
  76402. this.imageProcessingConfiguration.vignetteCentreY = value;
  76403. },
  76404. enumerable: true,
  76405. configurable: true
  76406. });
  76407. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76408. /**
  76409. * Gets Vignette weight or intensity of the vignette effect.
  76410. */
  76411. get: function () {
  76412. return this.imageProcessingConfiguration.vignetteWeight;
  76413. },
  76414. /**
  76415. * Sets Vignette weight or intensity of the vignette effect.
  76416. */
  76417. set: function (value) {
  76418. this.imageProcessingConfiguration.vignetteWeight = value;
  76419. },
  76420. enumerable: true,
  76421. configurable: true
  76422. });
  76423. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76424. /**
  76425. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76426. * if vignetteEnabled is set to true.
  76427. */
  76428. get: function () {
  76429. return this.imageProcessingConfiguration.vignetteColor;
  76430. },
  76431. /**
  76432. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76433. * if vignetteEnabled is set to true.
  76434. */
  76435. set: function (value) {
  76436. this.imageProcessingConfiguration.vignetteColor = value;
  76437. },
  76438. enumerable: true,
  76439. configurable: true
  76440. });
  76441. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76442. /**
  76443. * Gets Camera field of view used by the Vignette effect.
  76444. */
  76445. get: function () {
  76446. return this.imageProcessingConfiguration.vignetteCameraFov;
  76447. },
  76448. /**
  76449. * Sets Camera field of view used by the Vignette effect.
  76450. */
  76451. set: function (value) {
  76452. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76453. },
  76454. enumerable: true,
  76455. configurable: true
  76456. });
  76457. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76458. /**
  76459. * Gets the vignette blend mode allowing different kind of effect.
  76460. */
  76461. get: function () {
  76462. return this.imageProcessingConfiguration.vignetteBlendMode;
  76463. },
  76464. /**
  76465. * Sets the vignette blend mode allowing different kind of effect.
  76466. */
  76467. set: function (value) {
  76468. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76469. },
  76470. enumerable: true,
  76471. configurable: true
  76472. });
  76473. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76474. /**
  76475. * Gets wether the vignette effect is enabled.
  76476. */
  76477. get: function () {
  76478. return this.imageProcessingConfiguration.vignetteEnabled;
  76479. },
  76480. /**
  76481. * Sets wether the vignette effect is enabled.
  76482. */
  76483. set: function (value) {
  76484. this.imageProcessingConfiguration.vignetteEnabled = value;
  76485. },
  76486. enumerable: true,
  76487. configurable: true
  76488. });
  76489. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76490. /**
  76491. * Gets wether the input of the processing is in Gamma or Linear Space.
  76492. */
  76493. get: function () {
  76494. return this._fromLinearSpace;
  76495. },
  76496. /**
  76497. * Sets wether the input of the processing is in Gamma or Linear Space.
  76498. */
  76499. set: function (value) {
  76500. if (this._fromLinearSpace === value) {
  76501. return;
  76502. }
  76503. this._fromLinearSpace = value;
  76504. this._updateParameters();
  76505. },
  76506. enumerable: true,
  76507. configurable: true
  76508. });
  76509. ImageProcessingPostProcess.prototype.getClassName = function () {
  76510. return "ImageProcessingPostProcess";
  76511. };
  76512. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76513. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76514. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76515. var defines = "";
  76516. for (var define in this._defines) {
  76517. if (this._defines[define]) {
  76518. defines += "#define " + define + ";\r\n";
  76519. }
  76520. }
  76521. var samplers = ["textureSampler"];
  76522. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76523. var uniforms = ["scale"];
  76524. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76525. this.updateEffect(defines, uniforms, samplers);
  76526. };
  76527. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76528. _super.prototype.dispose.call(this, camera);
  76529. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76530. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76531. }
  76532. this.imageProcessingConfiguration.applyByPostProcess = false;
  76533. };
  76534. __decorate([
  76535. BABYLON.serialize()
  76536. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76537. return ImageProcessingPostProcess;
  76538. }(BABYLON.PostProcess));
  76539. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76540. })(BABYLON || (BABYLON = {}));
  76541. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76542. var BABYLON;
  76543. (function (BABYLON) {
  76544. /**
  76545. * Class used to store bone information
  76546. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  76547. */
  76548. var Bone = /** @class */ (function (_super) {
  76549. __extends(Bone, _super);
  76550. /**
  76551. * Create a new bone
  76552. * @param name defines the bone name
  76553. * @param skeleton defines the parent skeleton
  76554. * @param parentBone defines the parent (can be null if the bone is the root)
  76555. * @param localMatrix defines the local matrix
  76556. * @param restPose defines the rest pose matrix
  76557. * @param baseMatrix defines the base matrix
  76558. * @param index defines index of the bone in the hiearchy
  76559. */
  76560. function Bone(
  76561. /**
  76562. * defines the bone name
  76563. */
  76564. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76565. if (parentBone === void 0) { parentBone = null; }
  76566. if (localMatrix === void 0) { localMatrix = null; }
  76567. if (restPose === void 0) { restPose = null; }
  76568. if (baseMatrix === void 0) { baseMatrix = null; }
  76569. if (index === void 0) { index = null; }
  76570. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76571. _this.name = name;
  76572. /**
  76573. * Gets the list of child bones
  76574. */
  76575. _this.children = new Array();
  76576. /** Gets the animations associated with this bone */
  76577. _this.animations = new Array();
  76578. /**
  76579. * @ignore Internal only
  76580. * Set this value to map this bone to a different index in the transform matrices
  76581. * Set this value to -1 to exclude the bone from the transform matrices
  76582. */
  76583. _this._index = null;
  76584. _this._absoluteTransform = new BABYLON.Matrix();
  76585. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76586. _this._scalingDeterminant = 1;
  76587. _this._worldTransform = new BABYLON.Matrix();
  76588. _this._needToDecompose = true;
  76589. _this._needToCompose = false;
  76590. _this._skeleton = skeleton;
  76591. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76592. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76593. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76594. _this._index = index;
  76595. skeleton.bones.push(_this);
  76596. _this.setParent(parentBone, false);
  76597. if (baseMatrix || localMatrix) {
  76598. _this._updateDifferenceMatrix();
  76599. }
  76600. return _this;
  76601. }
  76602. Object.defineProperty(Bone.prototype, "_matrix", {
  76603. /** @ignore */
  76604. get: function () {
  76605. this._compose();
  76606. return this._localMatrix;
  76607. },
  76608. /** @ignore */
  76609. set: function (value) {
  76610. this._localMatrix.copyFrom(value);
  76611. this._needToDecompose = true;
  76612. },
  76613. enumerable: true,
  76614. configurable: true
  76615. });
  76616. // Members
  76617. /**
  76618. * Gets the parent skeleton
  76619. * @returns a skeleton
  76620. */
  76621. Bone.prototype.getSkeleton = function () {
  76622. return this._skeleton;
  76623. };
  76624. /**
  76625. * Gets parent bone
  76626. * @returns a bone or null if the bone is the root of the bone hierarchy
  76627. */
  76628. Bone.prototype.getParent = function () {
  76629. return this._parent;
  76630. };
  76631. /**
  76632. * Sets the parent bone
  76633. * @param parent defines the parent (can be null if the bone is the root)
  76634. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76635. */
  76636. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76637. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76638. if (this._parent === parent) {
  76639. return;
  76640. }
  76641. if (this._parent) {
  76642. var index = this._parent.children.indexOf(this);
  76643. if (index !== -1) {
  76644. this._parent.children.splice(index, 1);
  76645. }
  76646. }
  76647. this._parent = parent;
  76648. if (this._parent) {
  76649. this._parent.children.push(this);
  76650. }
  76651. if (updateDifferenceMatrix) {
  76652. this._updateDifferenceMatrix();
  76653. }
  76654. this.markAsDirty();
  76655. };
  76656. /**
  76657. * Gets the local matrix
  76658. * @returns a matrix
  76659. */
  76660. Bone.prototype.getLocalMatrix = function () {
  76661. this._compose();
  76662. return this._localMatrix;
  76663. };
  76664. /**
  76665. * Gets the base matrix (initial matrix which remains unchanged)
  76666. * @returns a matrix
  76667. */
  76668. Bone.prototype.getBaseMatrix = function () {
  76669. return this._baseMatrix;
  76670. };
  76671. /**
  76672. * Gets the rest pose matrix
  76673. * @returns a matrix
  76674. */
  76675. Bone.prototype.getRestPose = function () {
  76676. return this._restPose;
  76677. };
  76678. /**
  76679. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  76680. */
  76681. Bone.prototype.getWorldMatrix = function () {
  76682. return this._worldTransform;
  76683. };
  76684. /**
  76685. * Sets the local matrix to rest pose matrix
  76686. */
  76687. Bone.prototype.returnToRest = function () {
  76688. this.updateMatrix(this._restPose.clone());
  76689. };
  76690. /**
  76691. * Gets the inverse of the absolute transform matrix.
  76692. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  76693. * @returns a matrix
  76694. */
  76695. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76696. return this._invertedAbsoluteTransform;
  76697. };
  76698. /**
  76699. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  76700. * @returns a matrix
  76701. */
  76702. Bone.prototype.getAbsoluteTransform = function () {
  76703. return this._absoluteTransform;
  76704. };
  76705. Object.defineProperty(Bone.prototype, "position", {
  76706. // Properties (matches AbstractMesh properties)
  76707. /** Gets or sets current position (in local space) */
  76708. get: function () {
  76709. this._decompose();
  76710. return this._localPosition;
  76711. },
  76712. set: function (newPosition) {
  76713. this._decompose();
  76714. this._localPosition.copyFrom(newPosition);
  76715. this._markAsDirtyAndCompose();
  76716. },
  76717. enumerable: true,
  76718. configurable: true
  76719. });
  76720. Object.defineProperty(Bone.prototype, "rotation", {
  76721. /** Gets or sets current rotation (in local space) */
  76722. get: function () {
  76723. return this.getRotation();
  76724. },
  76725. set: function (newRotation) {
  76726. this.setRotation(newRotation);
  76727. },
  76728. enumerable: true,
  76729. configurable: true
  76730. });
  76731. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76732. /** Gets or sets current rotation quaternion (in local space) */
  76733. get: function () {
  76734. this._decompose();
  76735. return this._localRotation;
  76736. },
  76737. set: function (newRotation) {
  76738. this.setRotationQuaternion(newRotation);
  76739. },
  76740. enumerable: true,
  76741. configurable: true
  76742. });
  76743. Object.defineProperty(Bone.prototype, "scaling", {
  76744. /** Gets or sets current scaling (in local space) */
  76745. get: function () {
  76746. return this.getScale();
  76747. },
  76748. set: function (newScaling) {
  76749. this.setScale(newScaling);
  76750. },
  76751. enumerable: true,
  76752. configurable: true
  76753. });
  76754. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76755. /**
  76756. * Gets the animation properties override
  76757. */
  76758. get: function () {
  76759. return this._skeleton.animationPropertiesOverride;
  76760. },
  76761. enumerable: true,
  76762. configurable: true
  76763. });
  76764. // Methods
  76765. Bone.prototype._decompose = function () {
  76766. if (!this._needToDecompose) {
  76767. return;
  76768. }
  76769. this._needToDecompose = false;
  76770. if (!this._localScaling) {
  76771. this._localScaling = BABYLON.Vector3.Zero();
  76772. this._localRotation = BABYLON.Quaternion.Zero();
  76773. this._localPosition = BABYLON.Vector3.Zero();
  76774. }
  76775. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  76776. };
  76777. Bone.prototype._compose = function () {
  76778. if (!this._needToCompose) {
  76779. return;
  76780. }
  76781. this._needToCompose = false;
  76782. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  76783. };
  76784. /**
  76785. * Update the base and local matrices
  76786. * @param matrix defines the new base or local matrix
  76787. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76788. * @param updateLocalMatrix defines if the local matrix should be updated
  76789. */
  76790. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  76791. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76792. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  76793. this._baseMatrix.copyFrom(matrix);
  76794. if (updateDifferenceMatrix) {
  76795. this._updateDifferenceMatrix();
  76796. }
  76797. if (updateLocalMatrix) {
  76798. this._localMatrix.copyFrom(matrix);
  76799. this._markAsDirtyAndDecompose();
  76800. }
  76801. else {
  76802. this.markAsDirty();
  76803. }
  76804. };
  76805. /** @ignore */
  76806. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  76807. if (updateChildren === void 0) { updateChildren = true; }
  76808. if (!rootMatrix) {
  76809. rootMatrix = this._baseMatrix;
  76810. }
  76811. if (this._parent) {
  76812. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76813. }
  76814. else {
  76815. this._absoluteTransform.copyFrom(rootMatrix);
  76816. }
  76817. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76818. if (updateChildren) {
  76819. for (var index = 0; index < this.children.length; index++) {
  76820. this.children[index]._updateDifferenceMatrix();
  76821. }
  76822. }
  76823. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76824. };
  76825. /**
  76826. * Flag the bone as dirty (Forcing it to update everything)
  76827. */
  76828. Bone.prototype.markAsDirty = function () {
  76829. this._currentRenderId++;
  76830. this._childRenderId++;
  76831. this._skeleton._markAsDirty();
  76832. };
  76833. Bone.prototype._markAsDirtyAndCompose = function () {
  76834. this.markAsDirty();
  76835. this._needToCompose = true;
  76836. };
  76837. Bone.prototype._markAsDirtyAndDecompose = function () {
  76838. this.markAsDirty();
  76839. this._needToDecompose = true;
  76840. };
  76841. /**
  76842. * Copy an animation range from another bone
  76843. * @param source defines the source bone
  76844. * @param rangeName defines the range name to copy
  76845. * @param frameOffset defines the frame offset
  76846. * @param rescaleAsRequired defines if rescaling must be applied if required
  76847. * @param skelDimensionsRatio defines the scaling ratio
  76848. * @returns true if operation was successful
  76849. */
  76850. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76851. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76852. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76853. // all animation may be coming from a library skeleton, so may need to create animation
  76854. if (this.animations.length === 0) {
  76855. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76856. this.animations[0].setKeys([]);
  76857. }
  76858. // get animation info / verify there is such a range from the source bone
  76859. var sourceRange = source.animations[0].getRange(rangeName);
  76860. if (!sourceRange) {
  76861. return false;
  76862. }
  76863. var from = sourceRange.from;
  76864. var to = sourceRange.to;
  76865. var sourceKeys = source.animations[0].getKeys();
  76866. // rescaling prep
  76867. var sourceBoneLength = source.length;
  76868. var sourceParent = source.getParent();
  76869. var parent = this.getParent();
  76870. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76871. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76872. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76873. var destKeys = this.animations[0].getKeys();
  76874. // loop vars declaration
  76875. var orig;
  76876. var origTranslation;
  76877. var mat;
  76878. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76879. orig = sourceKeys[key];
  76880. if (orig.frame >= from && orig.frame <= to) {
  76881. if (rescaleAsRequired) {
  76882. mat = orig.value.clone();
  76883. // scale based on parent ratio, when bone has parent
  76884. if (parentScalingReqd) {
  76885. origTranslation = mat.getTranslation();
  76886. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76887. // scale based on skeleton dimension ratio when root bone, and value is passed
  76888. }
  76889. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76890. origTranslation = mat.getTranslation();
  76891. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76892. // use original when root bone, and no data for skelDimensionsRatio
  76893. }
  76894. else {
  76895. mat = orig.value;
  76896. }
  76897. }
  76898. else {
  76899. mat = orig.value;
  76900. }
  76901. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76902. }
  76903. }
  76904. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76905. return true;
  76906. };
  76907. /**
  76908. * Translate the bone in local or world space
  76909. * @param vec The amount to translate the bone
  76910. * @param space The space that the translation is in
  76911. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76912. */
  76913. Bone.prototype.translate = function (vec, space, mesh) {
  76914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76915. var lm = this.getLocalMatrix();
  76916. if (space == BABYLON.Space.LOCAL) {
  76917. lm.m[12] += vec.x;
  76918. lm.m[13] += vec.y;
  76919. lm.m[14] += vec.z;
  76920. }
  76921. else {
  76922. var wm = null;
  76923. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76924. if (mesh) {
  76925. wm = mesh.getWorldMatrix();
  76926. }
  76927. this._skeleton.computeAbsoluteTransforms();
  76928. var tmat = Bone._tmpMats[0];
  76929. var tvec = Bone._tmpVecs[0];
  76930. if (this._parent) {
  76931. if (mesh && wm) {
  76932. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76933. tmat.multiplyToRef(wm, tmat);
  76934. }
  76935. else {
  76936. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76937. }
  76938. }
  76939. tmat.m[12] = 0;
  76940. tmat.m[13] = 0;
  76941. tmat.m[14] = 0;
  76942. tmat.invert();
  76943. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76944. lm.m[12] += tvec.x;
  76945. lm.m[13] += tvec.y;
  76946. lm.m[14] += tvec.z;
  76947. }
  76948. this._markAsDirtyAndDecompose();
  76949. };
  76950. /**
  76951. * Set the postion of the bone in local or world space
  76952. * @param position The position to set the bone
  76953. * @param space The space that the position is in
  76954. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76955. */
  76956. Bone.prototype.setPosition = function (position, space, mesh) {
  76957. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76958. var lm = this.getLocalMatrix();
  76959. if (space == BABYLON.Space.LOCAL) {
  76960. lm.m[12] = position.x;
  76961. lm.m[13] = position.y;
  76962. lm.m[14] = position.z;
  76963. }
  76964. else {
  76965. var wm = null;
  76966. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76967. if (mesh) {
  76968. wm = mesh.getWorldMatrix();
  76969. }
  76970. this._skeleton.computeAbsoluteTransforms();
  76971. var tmat = Bone._tmpMats[0];
  76972. var vec = Bone._tmpVecs[0];
  76973. if (this._parent) {
  76974. if (mesh && wm) {
  76975. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76976. tmat.multiplyToRef(wm, tmat);
  76977. }
  76978. else {
  76979. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76980. }
  76981. }
  76982. tmat.invert();
  76983. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76984. lm.m[12] = vec.x;
  76985. lm.m[13] = vec.y;
  76986. lm.m[14] = vec.z;
  76987. }
  76988. this._markAsDirtyAndDecompose();
  76989. };
  76990. /**
  76991. * Set the absolute position of the bone (world space)
  76992. * @param position The position to set the bone
  76993. * @param mesh The mesh that this bone is attached to
  76994. */
  76995. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76996. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76997. };
  76998. /**
  76999. * Scale the bone on the x, y and z axes (in local space)
  77000. * @param x The amount to scale the bone on the x axis
  77001. * @param y The amount to scale the bone on the y axis
  77002. * @param z The amount to scale the bone on the z axis
  77003. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77004. */
  77005. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77006. if (scaleChildren === void 0) { scaleChildren = false; }
  77007. var locMat = this.getLocalMatrix();
  77008. // Apply new scaling on top of current local matrix
  77009. var scaleMat = Bone._tmpMats[0];
  77010. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77011. scaleMat.multiplyToRef(locMat, locMat);
  77012. // Invert scaling matrix and apply the inverse to all children
  77013. scaleMat.invert();
  77014. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77015. var child = _a[_i];
  77016. var cm = child.getLocalMatrix();
  77017. cm.multiplyToRef(scaleMat, cm);
  77018. cm.m[12] *= x;
  77019. cm.m[13] *= y;
  77020. cm.m[14] *= z;
  77021. child._markAsDirtyAndDecompose();
  77022. }
  77023. this._markAsDirtyAndDecompose();
  77024. if (scaleChildren) {
  77025. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77026. var child = _c[_b];
  77027. child.scale(x, y, z, scaleChildren);
  77028. }
  77029. }
  77030. };
  77031. /**
  77032. * Set the bone scaling in local space
  77033. * @param scale defines the scaling vector
  77034. */
  77035. Bone.prototype.setScale = function (scale) {
  77036. this._decompose();
  77037. this._localScaling.copyFrom(scale);
  77038. this._markAsDirtyAndCompose();
  77039. };
  77040. /**
  77041. * Gets the current scaling in local space
  77042. * @returns the current scaling vector
  77043. */
  77044. Bone.prototype.getScale = function () {
  77045. this._decompose();
  77046. return this._localScaling;
  77047. };
  77048. /**
  77049. * Gets the current scaling in local space and stores it in a target vector
  77050. * @param result defines the target vector
  77051. */
  77052. Bone.prototype.getScaleToRef = function (result) {
  77053. this._decompose();
  77054. result.copyFrom(this._localScaling);
  77055. };
  77056. /**
  77057. * Set the yaw, pitch, and roll of the bone in local or world space
  77058. * @param yaw The rotation of the bone on the y axis
  77059. * @param pitch The rotation of the bone on the x axis
  77060. * @param roll The rotation of the bone on the z axis
  77061. * @param space The space that the axes of rotation are in
  77062. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77063. */
  77064. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77066. if (space === BABYLON.Space.LOCAL) {
  77067. var quat = Bone._tmpQuat;
  77068. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77069. this.setRotationQuaternion(quat, space, mesh);
  77070. return;
  77071. }
  77072. var rotMatInv = Bone._tmpMats[0];
  77073. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77074. return;
  77075. }
  77076. var rotMat = Bone._tmpMats[1];
  77077. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77078. rotMatInv.multiplyToRef(rotMat, rotMat);
  77079. this._rotateWithMatrix(rotMat, space, mesh);
  77080. };
  77081. /**
  77082. * Add a rotation to the bone on an axis in local or world space
  77083. * @param axis The axis to rotate the bone on
  77084. * @param amount The amount to rotate the bone
  77085. * @param space The space that the axis is in
  77086. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77087. */
  77088. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77090. var rmat = Bone._tmpMats[0];
  77091. rmat.m[12] = 0;
  77092. rmat.m[13] = 0;
  77093. rmat.m[14] = 0;
  77094. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77095. this._rotateWithMatrix(rmat, space, mesh);
  77096. };
  77097. /**
  77098. * Set the rotation of the bone to a particular axis angle in local or world space
  77099. * @param axis The axis to rotate the bone on
  77100. * @param angle The angle that the bone should be rotated to
  77101. * @param space The space that the axis is in
  77102. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77103. */
  77104. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77106. if (space === BABYLON.Space.LOCAL) {
  77107. var quat = Bone._tmpQuat;
  77108. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77109. this.setRotationQuaternion(quat, space, mesh);
  77110. return;
  77111. }
  77112. var rotMatInv = Bone._tmpMats[0];
  77113. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77114. return;
  77115. }
  77116. var rotMat = Bone._tmpMats[1];
  77117. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77118. rotMatInv.multiplyToRef(rotMat, rotMat);
  77119. this._rotateWithMatrix(rotMat, space, mesh);
  77120. };
  77121. /**
  77122. * Set the euler rotation of the bone in local of world space
  77123. * @param rotation The euler rotation that the bone should be set to
  77124. * @param space The space that the rotation is in
  77125. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77126. */
  77127. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77128. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77129. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77130. };
  77131. /**
  77132. * Set the quaternion rotation of the bone in local of world space
  77133. * @param quat The quaternion rotation that the bone should be set to
  77134. * @param space The space that the rotation is in
  77135. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77136. */
  77137. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77139. if (space === BABYLON.Space.LOCAL) {
  77140. this._decompose();
  77141. this._localRotation.copyFrom(quat);
  77142. this._markAsDirtyAndCompose();
  77143. return;
  77144. }
  77145. var rotMatInv = Bone._tmpMats[0];
  77146. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77147. return;
  77148. }
  77149. var rotMat = Bone._tmpMats[1];
  77150. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77151. rotMatInv.multiplyToRef(rotMat, rotMat);
  77152. this._rotateWithMatrix(rotMat, space, mesh);
  77153. };
  77154. /**
  77155. * Set the rotation matrix of the bone in local of world space
  77156. * @param rotMat The rotation matrix that the bone should be set to
  77157. * @param space The space that the rotation is in
  77158. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77159. */
  77160. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77161. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77162. if (space === BABYLON.Space.LOCAL) {
  77163. var quat = Bone._tmpQuat;
  77164. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77165. this.setRotationQuaternion(quat, space, mesh);
  77166. return;
  77167. }
  77168. var rotMatInv = Bone._tmpMats[0];
  77169. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77170. return;
  77171. }
  77172. var rotMat2 = Bone._tmpMats[1];
  77173. rotMat2.copyFrom(rotMat);
  77174. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77175. this._rotateWithMatrix(rotMat2, space, mesh);
  77176. };
  77177. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77179. var lmat = this.getLocalMatrix();
  77180. var lx = lmat.m[12];
  77181. var ly = lmat.m[13];
  77182. var lz = lmat.m[14];
  77183. var parent = this.getParent();
  77184. var parentScale = Bone._tmpMats[3];
  77185. var parentScaleInv = Bone._tmpMats[4];
  77186. if (parent && space == BABYLON.Space.WORLD) {
  77187. if (mesh) {
  77188. parentScale.copyFrom(mesh.getWorldMatrix());
  77189. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77190. }
  77191. else {
  77192. parentScale.copyFrom(parent.getAbsoluteTransform());
  77193. }
  77194. parentScaleInv.copyFrom(parentScale);
  77195. parentScaleInv.invert();
  77196. lmat.multiplyToRef(parentScale, lmat);
  77197. lmat.multiplyToRef(rmat, lmat);
  77198. lmat.multiplyToRef(parentScaleInv, lmat);
  77199. }
  77200. else {
  77201. if (space == BABYLON.Space.WORLD && mesh) {
  77202. parentScale.copyFrom(mesh.getWorldMatrix());
  77203. parentScaleInv.copyFrom(parentScale);
  77204. parentScaleInv.invert();
  77205. lmat.multiplyToRef(parentScale, lmat);
  77206. lmat.multiplyToRef(rmat, lmat);
  77207. lmat.multiplyToRef(parentScaleInv, lmat);
  77208. }
  77209. else {
  77210. lmat.multiplyToRef(rmat, lmat);
  77211. }
  77212. }
  77213. lmat.m[12] = lx;
  77214. lmat.m[13] = ly;
  77215. lmat.m[14] = lz;
  77216. this.computeAbsoluteTransforms();
  77217. this._markAsDirtyAndDecompose();
  77218. };
  77219. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77220. var scaleMatrix = Bone._tmpMats[2];
  77221. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77222. if (mesh) {
  77223. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77224. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77225. }
  77226. rotMatInv.invert();
  77227. if (isNaN(rotMatInv.m[0])) {
  77228. // Matrix failed to invert.
  77229. // This can happen if scale is zero for example.
  77230. return false;
  77231. }
  77232. scaleMatrix.m[0] *= this._scalingDeterminant;
  77233. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77234. return true;
  77235. };
  77236. /**
  77237. * Get the position of the bone in local or world space
  77238. * @param space The space that the returned position is in
  77239. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77240. * @returns The position of the bone
  77241. */
  77242. Bone.prototype.getPosition = function (space, mesh) {
  77243. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77244. if (mesh === void 0) { mesh = null; }
  77245. var pos = BABYLON.Vector3.Zero();
  77246. this.getPositionToRef(space, mesh, pos);
  77247. return pos;
  77248. };
  77249. /**
  77250. * Copy the position of the bone to a vector3 in local or world space
  77251. * @param space The space that the returned position is in
  77252. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77253. * @param result The vector3 to copy the position to
  77254. */
  77255. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77256. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77257. if (space == BABYLON.Space.LOCAL) {
  77258. var lm = this.getLocalMatrix();
  77259. result.x = lm.m[12];
  77260. result.y = lm.m[13];
  77261. result.z = lm.m[14];
  77262. }
  77263. else {
  77264. var wm = null;
  77265. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77266. if (mesh) {
  77267. wm = mesh.getWorldMatrix();
  77268. }
  77269. this._skeleton.computeAbsoluteTransforms();
  77270. var tmat = Bone._tmpMats[0];
  77271. if (mesh && wm) {
  77272. tmat.copyFrom(this.getAbsoluteTransform());
  77273. tmat.multiplyToRef(wm, tmat);
  77274. }
  77275. else {
  77276. tmat = this.getAbsoluteTransform();
  77277. }
  77278. result.x = tmat.m[12];
  77279. result.y = tmat.m[13];
  77280. result.z = tmat.m[14];
  77281. }
  77282. };
  77283. /**
  77284. * Get the absolute position of the bone (world space)
  77285. * @param mesh The mesh that this bone is attached to
  77286. * @returns The absolute position of the bone
  77287. */
  77288. Bone.prototype.getAbsolutePosition = function (mesh) {
  77289. if (mesh === void 0) { mesh = null; }
  77290. var pos = BABYLON.Vector3.Zero();
  77291. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77292. return pos;
  77293. };
  77294. /**
  77295. * Copy the absolute position of the bone (world space) to the result param
  77296. * @param mesh The mesh that this bone is attached to
  77297. * @param result The vector3 to copy the absolute position to
  77298. */
  77299. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77300. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77301. };
  77302. /**
  77303. * Compute the absolute transforms of this bone and its children
  77304. */
  77305. Bone.prototype.computeAbsoluteTransforms = function () {
  77306. this._compose();
  77307. if (this._parent) {
  77308. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77309. }
  77310. else {
  77311. this._absoluteTransform.copyFrom(this._localMatrix);
  77312. var poseMatrix = this._skeleton.getPoseMatrix();
  77313. if (poseMatrix) {
  77314. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77315. }
  77316. }
  77317. var children = this.children;
  77318. var len = children.length;
  77319. for (var i = 0; i < len; i++) {
  77320. children[i].computeAbsoluteTransforms();
  77321. }
  77322. };
  77323. /**
  77324. * Get the world direction from an axis that is in the local space of the bone
  77325. * @param localAxis The local direction that is used to compute the world direction
  77326. * @param mesh The mesh that this bone is attached to
  77327. * @returns The world direction
  77328. */
  77329. Bone.prototype.getDirection = function (localAxis, mesh) {
  77330. if (mesh === void 0) { mesh = null; }
  77331. var result = BABYLON.Vector3.Zero();
  77332. this.getDirectionToRef(localAxis, mesh, result);
  77333. return result;
  77334. };
  77335. /**
  77336. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77337. * @param localAxis The local direction that is used to compute the world direction
  77338. * @param mesh The mesh that this bone is attached to
  77339. * @param result The vector3 that the world direction will be copied to
  77340. */
  77341. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77342. if (mesh === void 0) { mesh = null; }
  77343. var wm = null;
  77344. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77345. if (mesh) {
  77346. wm = mesh.getWorldMatrix();
  77347. }
  77348. this._skeleton.computeAbsoluteTransforms();
  77349. var mat = Bone._tmpMats[0];
  77350. mat.copyFrom(this.getAbsoluteTransform());
  77351. if (mesh && wm) {
  77352. mat.multiplyToRef(wm, mat);
  77353. }
  77354. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77355. result.normalize();
  77356. };
  77357. /**
  77358. * Get the euler rotation of the bone in local or world space
  77359. * @param space The space that the rotation should be in
  77360. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77361. * @returns The euler rotation
  77362. */
  77363. Bone.prototype.getRotation = function (space, mesh) {
  77364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77365. if (mesh === void 0) { mesh = null; }
  77366. var result = BABYLON.Vector3.Zero();
  77367. this.getRotationToRef(space, mesh, result);
  77368. return result;
  77369. };
  77370. /**
  77371. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77372. * @param space The space that the rotation should be in
  77373. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77374. * @param result The vector3 that the rotation should be copied to
  77375. */
  77376. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77378. if (mesh === void 0) { mesh = null; }
  77379. var quat = Bone._tmpQuat;
  77380. this.getRotationQuaternionToRef(space, mesh, quat);
  77381. quat.toEulerAnglesToRef(result);
  77382. };
  77383. /**
  77384. * Get the quaternion rotation of the bone in either local or world space
  77385. * @param space The space that the rotation should be in
  77386. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77387. * @returns The quaternion rotation
  77388. */
  77389. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77390. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77391. if (mesh === void 0) { mesh = null; }
  77392. var result = BABYLON.Quaternion.Identity();
  77393. this.getRotationQuaternionToRef(space, mesh, result);
  77394. return result;
  77395. };
  77396. /**
  77397. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77398. * @param space The space that the rotation should be in
  77399. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77400. * @param result The quaternion that the rotation should be copied to
  77401. */
  77402. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  77403. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77404. if (mesh === void 0) { mesh = null; }
  77405. if (space == BABYLON.Space.LOCAL) {
  77406. this._decompose();
  77407. result.copyFrom(this._localRotation);
  77408. }
  77409. else {
  77410. var mat = Bone._tmpMats[0];
  77411. var amat = this.getAbsoluteTransform();
  77412. if (mesh) {
  77413. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77414. }
  77415. else {
  77416. mat.copyFrom(amat);
  77417. }
  77418. mat.m[0] *= this._scalingDeterminant;
  77419. mat.m[1] *= this._scalingDeterminant;
  77420. mat.m[2] *= this._scalingDeterminant;
  77421. mat.decompose(undefined, result, undefined);
  77422. }
  77423. };
  77424. /**
  77425. * Get the rotation matrix of the bone in local or world space
  77426. * @param space The space that the rotation should be in
  77427. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77428. * @returns The rotation matrix
  77429. */
  77430. Bone.prototype.getRotationMatrix = function (space, mesh) {
  77431. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77432. var result = BABYLON.Matrix.Identity();
  77433. this.getRotationMatrixToRef(space, mesh, result);
  77434. return result;
  77435. };
  77436. /**
  77437. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  77438. * @param space The space that the rotation should be in
  77439. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77440. * @param result The quaternion that the rotation should be copied to
  77441. */
  77442. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77444. if (space == BABYLON.Space.LOCAL) {
  77445. this.getLocalMatrix().getRotationMatrixToRef(result);
  77446. }
  77447. else {
  77448. var mat = Bone._tmpMats[0];
  77449. var amat = this.getAbsoluteTransform();
  77450. if (mesh) {
  77451. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77452. }
  77453. else {
  77454. mat.copyFrom(amat);
  77455. }
  77456. mat.m[0] *= this._scalingDeterminant;
  77457. mat.m[1] *= this._scalingDeterminant;
  77458. mat.m[2] *= this._scalingDeterminant;
  77459. mat.getRotationMatrixToRef(result);
  77460. }
  77461. };
  77462. /**
  77463. * Get the world position of a point that is in the local space of the bone
  77464. * @param position The local position
  77465. * @param mesh The mesh that this bone is attached to
  77466. * @returns The world position
  77467. */
  77468. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77469. if (mesh === void 0) { mesh = null; }
  77470. var result = BABYLON.Vector3.Zero();
  77471. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77472. return result;
  77473. };
  77474. /**
  77475. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  77476. * @param position The local position
  77477. * @param mesh The mesh that this bone is attached to
  77478. * @param result The vector3 that the world position should be copied to
  77479. */
  77480. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77481. if (mesh === void 0) { mesh = null; }
  77482. var wm = null;
  77483. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77484. if (mesh) {
  77485. wm = mesh.getWorldMatrix();
  77486. }
  77487. this._skeleton.computeAbsoluteTransforms();
  77488. var tmat = Bone._tmpMats[0];
  77489. if (mesh && wm) {
  77490. tmat.copyFrom(this.getAbsoluteTransform());
  77491. tmat.multiplyToRef(wm, tmat);
  77492. }
  77493. else {
  77494. tmat = this.getAbsoluteTransform();
  77495. }
  77496. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77497. };
  77498. /**
  77499. * Get the local position of a point that is in world space
  77500. * @param position The world position
  77501. * @param mesh The mesh that this bone is attached to
  77502. * @returns The local position
  77503. */
  77504. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77505. if (mesh === void 0) { mesh = null; }
  77506. var result = BABYLON.Vector3.Zero();
  77507. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77508. return result;
  77509. };
  77510. /**
  77511. * Get the local position of a point that is in world space and copy it to the result param
  77512. * @param position The world position
  77513. * @param mesh The mesh that this bone is attached to
  77514. * @param result The vector3 that the local position should be copied to
  77515. */
  77516. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77517. if (mesh === void 0) { mesh = null; }
  77518. var wm = null;
  77519. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77520. if (mesh) {
  77521. wm = mesh.getWorldMatrix();
  77522. }
  77523. this._skeleton.computeAbsoluteTransforms();
  77524. var tmat = Bone._tmpMats[0];
  77525. tmat.copyFrom(this.getAbsoluteTransform());
  77526. if (mesh && wm) {
  77527. tmat.multiplyToRef(wm, tmat);
  77528. }
  77529. tmat.invert();
  77530. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77531. };
  77532. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77533. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77534. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77535. return Bone;
  77536. }(BABYLON.Node));
  77537. BABYLON.Bone = Bone;
  77538. })(BABYLON || (BABYLON = {}));
  77539. //# sourceMappingURL=babylon.bone.js.map
  77540. var BABYLON;
  77541. (function (BABYLON) {
  77542. /**
  77543. * Class used to apply inverse kinematics to bones
  77544. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  77545. */
  77546. var BoneIKController = /** @class */ (function () {
  77547. /**
  77548. * Creates a new BoneIKController
  77549. * @param mesh defines the mesh to control
  77550. * @param bone defines the bone to control
  77551. * @param options defines options to set up the controller
  77552. */
  77553. function BoneIKController(mesh, bone, options) {
  77554. /**
  77555. * Gets or sets the target position
  77556. */
  77557. this.targetPosition = BABYLON.Vector3.Zero();
  77558. /**
  77559. * Gets or sets the pole target position
  77560. */
  77561. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77562. /**
  77563. * Gets or sets the pole target local offset
  77564. */
  77565. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77566. /**
  77567. * Gets or sets the pole angle
  77568. */
  77569. this.poleAngle = 0;
  77570. /**
  77571. * 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)
  77572. */
  77573. this.slerpAmount = 1;
  77574. this._bone1Quat = BABYLON.Quaternion.Identity();
  77575. this._bone1Mat = BABYLON.Matrix.Identity();
  77576. this._bone2Ang = Math.PI;
  77577. this._maxAngle = Math.PI;
  77578. this._rightHandedSystem = false;
  77579. this._bendAxis = BABYLON.Vector3.Right();
  77580. this._slerping = false;
  77581. this._adjustRoll = 0;
  77582. this._bone2 = bone;
  77583. this._bone1 = bone.getParent();
  77584. if (!this._bone1) {
  77585. return;
  77586. }
  77587. this.mesh = mesh;
  77588. var bonePos = bone.getPosition();
  77589. if (bone.getAbsoluteTransform().determinant() > 0) {
  77590. this._rightHandedSystem = true;
  77591. this._bendAxis.x = 0;
  77592. this._bendAxis.y = 0;
  77593. this._bendAxis.z = -1;
  77594. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77595. this._adjustRoll = Math.PI * .5;
  77596. this._bendAxis.z = 1;
  77597. }
  77598. }
  77599. if (this._bone1.length) {
  77600. var boneScale1 = this._bone1.getScale();
  77601. var boneScale2 = this._bone2.getScale();
  77602. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77603. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77604. }
  77605. else if (this._bone1.children[0]) {
  77606. mesh.computeWorldMatrix(true);
  77607. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77608. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77609. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77610. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77611. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77612. }
  77613. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77614. this.maxAngle = Math.PI;
  77615. if (options) {
  77616. if (options.targetMesh) {
  77617. this.targetMesh = options.targetMesh;
  77618. this.targetMesh.computeWorldMatrix(true);
  77619. }
  77620. if (options.poleTargetMesh) {
  77621. this.poleTargetMesh = options.poleTargetMesh;
  77622. this.poleTargetMesh.computeWorldMatrix(true);
  77623. }
  77624. else if (options.poleTargetBone) {
  77625. this.poleTargetBone = options.poleTargetBone;
  77626. }
  77627. else if (this._bone1.getParent()) {
  77628. this.poleTargetBone = this._bone1.getParent();
  77629. }
  77630. if (options.poleTargetLocalOffset) {
  77631. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77632. }
  77633. if (options.poleAngle) {
  77634. this.poleAngle = options.poleAngle;
  77635. }
  77636. if (options.bendAxis) {
  77637. this._bendAxis.copyFrom(options.bendAxis);
  77638. }
  77639. if (options.maxAngle) {
  77640. this.maxAngle = options.maxAngle;
  77641. }
  77642. if (options.slerpAmount) {
  77643. this.slerpAmount = options.slerpAmount;
  77644. }
  77645. }
  77646. }
  77647. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77648. /**
  77649. * Gets or sets maximum allowed angle
  77650. */
  77651. get: function () {
  77652. return this._maxAngle;
  77653. },
  77654. set: function (value) {
  77655. this._setMaxAngle(value);
  77656. },
  77657. enumerable: true,
  77658. configurable: true
  77659. });
  77660. BoneIKController.prototype._setMaxAngle = function (ang) {
  77661. if (ang < 0) {
  77662. ang = 0;
  77663. }
  77664. if (ang > Math.PI || ang == undefined) {
  77665. ang = Math.PI;
  77666. }
  77667. this._maxAngle = ang;
  77668. var a = this._bone1Length;
  77669. var b = this._bone2Length;
  77670. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77671. };
  77672. /**
  77673. * Force the controller to update the bones
  77674. */
  77675. BoneIKController.prototype.update = function () {
  77676. var bone1 = this._bone1;
  77677. if (!bone1) {
  77678. return;
  77679. }
  77680. var target = this.targetPosition;
  77681. var poleTarget = this.poleTargetPosition;
  77682. var mat1 = BoneIKController._tmpMats[0];
  77683. var mat2 = BoneIKController._tmpMats[1];
  77684. if (this.targetMesh) {
  77685. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77686. }
  77687. if (this.poleTargetBone) {
  77688. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77689. }
  77690. else if (this.poleTargetMesh) {
  77691. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77692. }
  77693. var bonePos = BoneIKController._tmpVecs[0];
  77694. var zaxis = BoneIKController._tmpVecs[1];
  77695. var xaxis = BoneIKController._tmpVecs[2];
  77696. var yaxis = BoneIKController._tmpVecs[3];
  77697. var upAxis = BoneIKController._tmpVecs[4];
  77698. var _tmpQuat = BoneIKController._tmpQuat;
  77699. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77700. poleTarget.subtractToRef(bonePos, upAxis);
  77701. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77702. upAxis.y = 1;
  77703. }
  77704. else {
  77705. upAxis.normalize();
  77706. }
  77707. target.subtractToRef(bonePos, yaxis);
  77708. yaxis.normalize();
  77709. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77710. zaxis.normalize();
  77711. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77712. xaxis.normalize();
  77713. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77714. var a = this._bone1Length;
  77715. var b = this._bone2Length;
  77716. var c = BABYLON.Vector3.Distance(bonePos, target);
  77717. if (this._maxReach > 0) {
  77718. c = Math.min(this._maxReach, c);
  77719. }
  77720. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77721. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77722. if (acosa > 1) {
  77723. acosa = 1;
  77724. }
  77725. if (acosb > 1) {
  77726. acosb = 1;
  77727. }
  77728. if (acosa < -1) {
  77729. acosa = -1;
  77730. }
  77731. if (acosb < -1) {
  77732. acosb = -1;
  77733. }
  77734. var angA = Math.acos(acosa);
  77735. var angB = Math.acos(acosb);
  77736. var angC = -angA - angB;
  77737. if (this._rightHandedSystem) {
  77738. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77739. mat2.multiplyToRef(mat1, mat1);
  77740. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77741. mat2.multiplyToRef(mat1, mat1);
  77742. }
  77743. else {
  77744. var _tmpVec = BoneIKController._tmpVecs[5];
  77745. _tmpVec.copyFrom(this._bendAxis);
  77746. _tmpVec.x *= -1;
  77747. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77748. mat2.multiplyToRef(mat1, mat1);
  77749. }
  77750. if (this.poleAngle) {
  77751. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77752. mat1.multiplyToRef(mat2, mat1);
  77753. }
  77754. if (this._bone1) {
  77755. if (this.slerpAmount < 1) {
  77756. if (!this._slerping) {
  77757. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77758. }
  77759. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77760. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77761. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77762. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77763. this._slerping = true;
  77764. }
  77765. else {
  77766. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77767. this._bone1Mat.copyFrom(mat1);
  77768. this._slerping = false;
  77769. }
  77770. }
  77771. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77772. this._bone2Ang = angC;
  77773. };
  77774. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77775. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77776. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77777. return BoneIKController;
  77778. }());
  77779. BABYLON.BoneIKController = BoneIKController;
  77780. })(BABYLON || (BABYLON = {}));
  77781. //# sourceMappingURL=babylon.boneIKController.js.map
  77782. var BABYLON;
  77783. (function (BABYLON) {
  77784. /**
  77785. * Class used to make a bone look toward a point in space
  77786. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  77787. */
  77788. var BoneLookController = /** @class */ (function () {
  77789. /**
  77790. * Create a BoneLookController
  77791. * @param mesh the mesh that the bone belongs to
  77792. * @param bone the bone that will be looking to the target
  77793. * @param target the target Vector3 to look at
  77794. * @param settings optional settings:
  77795. * * maxYaw: the maximum angle the bone will yaw to
  77796. * * minYaw: the minimum angle the bone will yaw to
  77797. * * maxPitch: the maximum angle the bone will pitch to
  77798. * * minPitch: the minimum angle the bone will yaw to
  77799. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77800. * * upAxis: the up axis of the coordinate system
  77801. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77802. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  77803. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77804. * * adjustYaw: used to make an adjustment to the yaw of the bone
  77805. * * adjustPitch: used to make an adjustment to the pitch of the bone
  77806. * * adjustRoll: used to make an adjustment to the roll of the bone
  77807. **/
  77808. function BoneLookController(mesh, bone, target, options) {
  77809. /**
  77810. * The up axis of the coordinate system that is used when the bone is rotated
  77811. */
  77812. this.upAxis = BABYLON.Vector3.Up();
  77813. /**
  77814. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  77815. */
  77816. this.upAxisSpace = BABYLON.Space.LOCAL;
  77817. /**
  77818. * Used to make an adjustment to the yaw of the bone
  77819. */
  77820. this.adjustYaw = 0;
  77821. /**
  77822. * Used to make an adjustment to the pitch of the bone
  77823. */
  77824. this.adjustPitch = 0;
  77825. /**
  77826. * Used to make an adjustment to the roll of the bone
  77827. */
  77828. this.adjustRoll = 0;
  77829. /**
  77830. * 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)
  77831. */
  77832. this.slerpAmount = 1;
  77833. this._boneQuat = BABYLON.Quaternion.Identity();
  77834. this._slerping = false;
  77835. this._firstFrameSkipped = false;
  77836. this._fowardAxis = BABYLON.Vector3.Forward();
  77837. this.mesh = mesh;
  77838. this.bone = bone;
  77839. this.target = target;
  77840. if (options) {
  77841. if (options.adjustYaw) {
  77842. this.adjustYaw = options.adjustYaw;
  77843. }
  77844. if (options.adjustPitch) {
  77845. this.adjustPitch = options.adjustPitch;
  77846. }
  77847. if (options.adjustRoll) {
  77848. this.adjustRoll = options.adjustRoll;
  77849. }
  77850. if (options.maxYaw != null) {
  77851. this.maxYaw = options.maxYaw;
  77852. }
  77853. else {
  77854. this.maxYaw = Math.PI;
  77855. }
  77856. if (options.minYaw != null) {
  77857. this.minYaw = options.minYaw;
  77858. }
  77859. else {
  77860. this.minYaw = -Math.PI;
  77861. }
  77862. if (options.maxPitch != null) {
  77863. this.maxPitch = options.maxPitch;
  77864. }
  77865. else {
  77866. this.maxPitch = Math.PI;
  77867. }
  77868. if (options.minPitch != null) {
  77869. this.minPitch = options.minPitch;
  77870. }
  77871. else {
  77872. this.minPitch = -Math.PI;
  77873. }
  77874. if (options.slerpAmount != null) {
  77875. this.slerpAmount = options.slerpAmount;
  77876. }
  77877. if (options.upAxis != null) {
  77878. this.upAxis = options.upAxis;
  77879. }
  77880. if (options.upAxisSpace != null) {
  77881. this.upAxisSpace = options.upAxisSpace;
  77882. }
  77883. if (options.yawAxis != null || options.pitchAxis != null) {
  77884. var newYawAxis = BABYLON.Axis.Y;
  77885. var newPitchAxis = BABYLON.Axis.X;
  77886. if (options.yawAxis != null) {
  77887. newYawAxis = options.yawAxis.clone();
  77888. newYawAxis.normalize();
  77889. }
  77890. if (options.pitchAxis != null) {
  77891. newPitchAxis = options.pitchAxis.clone();
  77892. newPitchAxis.normalize();
  77893. }
  77894. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77895. this._transformYawPitch = BABYLON.Matrix.Identity();
  77896. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77897. this._transformYawPitchInv = this._transformYawPitch.clone();
  77898. this._transformYawPitch.invert();
  77899. }
  77900. }
  77901. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77902. this.upAxisSpace = BABYLON.Space.LOCAL;
  77903. }
  77904. }
  77905. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77906. /**
  77907. * Gets or sets the minimum yaw angle that the bone can look to
  77908. */
  77909. get: function () {
  77910. return this._minYaw;
  77911. },
  77912. set: function (value) {
  77913. this._minYaw = value;
  77914. this._minYawSin = Math.sin(value);
  77915. this._minYawCos = Math.cos(value);
  77916. if (this._maxYaw != null) {
  77917. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77918. this._yawRange = this._maxYaw - this._minYaw;
  77919. }
  77920. },
  77921. enumerable: true,
  77922. configurable: true
  77923. });
  77924. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77925. /**
  77926. * Gets or sets the maximum yaw angle that the bone can look to
  77927. */
  77928. get: function () {
  77929. return this._maxYaw;
  77930. },
  77931. set: function (value) {
  77932. this._maxYaw = value;
  77933. this._maxYawSin = Math.sin(value);
  77934. this._maxYawCos = Math.cos(value);
  77935. if (this._minYaw != null) {
  77936. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77937. this._yawRange = this._maxYaw - this._minYaw;
  77938. }
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77944. /**
  77945. * Gets or sets the minimum pitch angle that the bone can look to
  77946. */
  77947. get: function () {
  77948. return this._minPitch;
  77949. },
  77950. set: function (value) {
  77951. this._minPitch = value;
  77952. this._minPitchTan = Math.tan(value);
  77953. },
  77954. enumerable: true,
  77955. configurable: true
  77956. });
  77957. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77958. /**
  77959. * Gets or sets the maximum pitch angle that the bone can look to
  77960. */
  77961. get: function () {
  77962. return this._maxPitch;
  77963. },
  77964. set: function (value) {
  77965. this._maxPitch = value;
  77966. this._maxPitchTan = Math.tan(value);
  77967. },
  77968. enumerable: true,
  77969. configurable: true
  77970. });
  77971. /**
  77972. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  77973. */
  77974. BoneLookController.prototype.update = function () {
  77975. //skip the first frame when slerping so that the mesh rotation is correct
  77976. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77977. this._firstFrameSkipped = true;
  77978. return;
  77979. }
  77980. var bone = this.bone;
  77981. var bonePos = BoneLookController._tmpVecs[0];
  77982. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77983. var target = this.target;
  77984. var _tmpMat1 = BoneLookController._tmpMats[0];
  77985. var _tmpMat2 = BoneLookController._tmpMats[1];
  77986. var mesh = this.mesh;
  77987. var parentBone = bone.getParent();
  77988. var upAxis = BoneLookController._tmpVecs[1];
  77989. upAxis.copyFrom(this.upAxis);
  77990. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77991. if (this._transformYawPitch) {
  77992. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77993. }
  77994. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77995. }
  77996. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77997. mesh.getDirectionToRef(upAxis, upAxis);
  77998. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77999. upAxis.normalize();
  78000. }
  78001. }
  78002. var checkYaw = false;
  78003. var checkPitch = false;
  78004. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78005. checkYaw = true;
  78006. }
  78007. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78008. checkPitch = true;
  78009. }
  78010. if (checkYaw || checkPitch) {
  78011. var spaceMat = BoneLookController._tmpMats[2];
  78012. var spaceMatInv = BoneLookController._tmpMats[3];
  78013. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78014. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78015. }
  78016. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78017. spaceMat.copyFrom(mesh.getWorldMatrix());
  78018. }
  78019. else {
  78020. var forwardAxis = BoneLookController._tmpVecs[2];
  78021. forwardAxis.copyFrom(this._fowardAxis);
  78022. if (this._transformYawPitch) {
  78023. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78024. }
  78025. if (parentBone) {
  78026. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78027. }
  78028. else {
  78029. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78030. }
  78031. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78032. rightAxis.normalize();
  78033. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78034. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78035. }
  78036. spaceMat.invertToRef(spaceMatInv);
  78037. var xzlen = null;
  78038. if (checkPitch) {
  78039. var localTarget = BoneLookController._tmpVecs[3];
  78040. target.subtractToRef(bonePos, localTarget);
  78041. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78042. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78043. var pitch = Math.atan2(localTarget.y, xzlen);
  78044. var newPitch = pitch;
  78045. if (pitch > this._maxPitch) {
  78046. localTarget.y = this._maxPitchTan * xzlen;
  78047. newPitch = this._maxPitch;
  78048. }
  78049. else if (pitch < this._minPitch) {
  78050. localTarget.y = this._minPitchTan * xzlen;
  78051. newPitch = this._minPitch;
  78052. }
  78053. if (pitch != newPitch) {
  78054. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78055. localTarget.addInPlace(bonePos);
  78056. target = localTarget;
  78057. }
  78058. }
  78059. if (checkYaw) {
  78060. var localTarget = BoneLookController._tmpVecs[4];
  78061. target.subtractToRef(bonePos, localTarget);
  78062. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78063. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78064. var newYaw = yaw;
  78065. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78066. if (xzlen == null) {
  78067. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78068. }
  78069. if (this._yawRange > Math.PI) {
  78070. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78071. localTarget.z = this._maxYawCos * xzlen;
  78072. localTarget.x = this._maxYawSin * xzlen;
  78073. newYaw = this._maxYaw;
  78074. }
  78075. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78076. localTarget.z = this._minYawCos * xzlen;
  78077. localTarget.x = this._minYawSin * xzlen;
  78078. newYaw = this._minYaw;
  78079. }
  78080. }
  78081. else {
  78082. if (yaw > this._maxYaw) {
  78083. localTarget.z = this._maxYawCos * xzlen;
  78084. localTarget.x = this._maxYawSin * xzlen;
  78085. newYaw = this._maxYaw;
  78086. }
  78087. else if (yaw < this._minYaw) {
  78088. localTarget.z = this._minYawCos * xzlen;
  78089. localTarget.x = this._minYawSin * xzlen;
  78090. newYaw = this._minYaw;
  78091. }
  78092. }
  78093. }
  78094. if (this._slerping && this._yawRange > Math.PI) {
  78095. //are we going to be crossing into the min/max region?
  78096. var boneFwd = BoneLookController._tmpVecs[8];
  78097. boneFwd.copyFrom(BABYLON.Axis.Z);
  78098. if (this._transformYawPitch) {
  78099. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78100. }
  78101. var boneRotMat = BoneLookController._tmpMats[4];
  78102. this._boneQuat.toRotationMatrix(boneRotMat);
  78103. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78104. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78105. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78106. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78107. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78108. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78109. if (angBtwTar > angBtwMidYaw) {
  78110. if (xzlen == null) {
  78111. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78112. }
  78113. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78114. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78115. if (angBtwMin < angBtwMax) {
  78116. newYaw = boneYaw + Math.PI * .75;
  78117. localTarget.z = Math.cos(newYaw) * xzlen;
  78118. localTarget.x = Math.sin(newYaw) * xzlen;
  78119. }
  78120. else {
  78121. newYaw = boneYaw - Math.PI * .75;
  78122. localTarget.z = Math.cos(newYaw) * xzlen;
  78123. localTarget.x = Math.sin(newYaw) * xzlen;
  78124. }
  78125. }
  78126. }
  78127. if (yaw != newYaw) {
  78128. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78129. localTarget.addInPlace(bonePos);
  78130. target = localTarget;
  78131. }
  78132. }
  78133. }
  78134. var zaxis = BoneLookController._tmpVecs[5];
  78135. var xaxis = BoneLookController._tmpVecs[6];
  78136. var yaxis = BoneLookController._tmpVecs[7];
  78137. var _tmpQuat = BoneLookController._tmpQuat;
  78138. target.subtractToRef(bonePos, zaxis);
  78139. zaxis.normalize();
  78140. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78141. xaxis.normalize();
  78142. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78143. yaxis.normalize();
  78144. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78145. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78146. return;
  78147. }
  78148. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78149. return;
  78150. }
  78151. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78152. return;
  78153. }
  78154. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78155. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78156. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78157. }
  78158. if (this.slerpAmount < 1) {
  78159. if (!this._slerping) {
  78160. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78161. }
  78162. if (this._transformYawPitch) {
  78163. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78164. }
  78165. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78166. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78167. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78168. this._slerping = true;
  78169. }
  78170. else {
  78171. if (this._transformYawPitch) {
  78172. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78173. }
  78174. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78175. this._slerping = false;
  78176. }
  78177. };
  78178. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78179. var angDiff = ang2 - ang1;
  78180. angDiff %= Math.PI * 2;
  78181. if (angDiff > Math.PI) {
  78182. angDiff -= Math.PI * 2;
  78183. }
  78184. else if (angDiff < -Math.PI) {
  78185. angDiff += Math.PI * 2;
  78186. }
  78187. return angDiff;
  78188. };
  78189. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78190. ang1 %= (2 * Math.PI);
  78191. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78192. ang2 %= (2 * Math.PI);
  78193. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78194. var ab = 0;
  78195. if (ang1 < ang2) {
  78196. ab = ang2 - ang1;
  78197. }
  78198. else {
  78199. ab = ang1 - ang2;
  78200. }
  78201. if (ab > Math.PI) {
  78202. ab = Math.PI * 2 - ab;
  78203. }
  78204. return ab;
  78205. };
  78206. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78207. ang %= (2 * Math.PI);
  78208. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78209. ang1 %= (2 * Math.PI);
  78210. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78211. ang2 %= (2 * Math.PI);
  78212. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78213. if (ang1 < ang2) {
  78214. if (ang > ang1 && ang < ang2) {
  78215. return true;
  78216. }
  78217. }
  78218. else {
  78219. if (ang > ang2 && ang < ang1) {
  78220. return true;
  78221. }
  78222. }
  78223. return false;
  78224. };
  78225. 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()];
  78226. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78227. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78228. return BoneLookController;
  78229. }());
  78230. BABYLON.BoneLookController = BoneLookController;
  78231. })(BABYLON || (BABYLON = {}));
  78232. //# sourceMappingURL=babylon.boneLookController.js.map
  78233. var BABYLON;
  78234. (function (BABYLON) {
  78235. /**
  78236. * Class used to handle skinning animations
  78237. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78238. */
  78239. var Skeleton = /** @class */ (function () {
  78240. /**
  78241. * Creates a new skeleton
  78242. * @param name defines the skeleton name
  78243. * @param id defines the skeleton Id
  78244. * @param scene defines the hosting scene
  78245. */
  78246. function Skeleton(
  78247. /** defines the skeleton name */
  78248. name,
  78249. /** defines the skeleton Id */
  78250. id, scene) {
  78251. this.name = name;
  78252. this.id = id;
  78253. /**
  78254. * Gets the list of child bones
  78255. */
  78256. this.bones = new Array();
  78257. /**
  78258. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78259. */
  78260. this.needInitialSkinMatrix = false;
  78261. this._isDirty = true;
  78262. this._meshesWithPoseMatrix = new Array();
  78263. this._identity = BABYLON.Matrix.Identity();
  78264. this._ranges = {};
  78265. this._lastAbsoluteTransformsUpdateId = -1;
  78266. /**
  78267. * Specifies if the skeleton should be serialized
  78268. */
  78269. this.doNotSerialize = false;
  78270. this._animationPropertiesOverride = null;
  78271. // Events
  78272. /**
  78273. * An observable triggered before computing the skeleton's matrices
  78274. */
  78275. this.onBeforeComputeObservable = new BABYLON.Observable();
  78276. this.bones = [];
  78277. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78278. scene.skeletons.push(this);
  78279. //make sure it will recalculate the matrix next time prepare is called.
  78280. this._isDirty = true;
  78281. }
  78282. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78283. /**
  78284. * Gets or sets the animation properties override
  78285. */
  78286. get: function () {
  78287. if (!this._animationPropertiesOverride) {
  78288. return this._scene.animationPropertiesOverride;
  78289. }
  78290. return this._animationPropertiesOverride;
  78291. },
  78292. set: function (value) {
  78293. this._animationPropertiesOverride = value;
  78294. },
  78295. enumerable: true,
  78296. configurable: true
  78297. });
  78298. // Members
  78299. /**
  78300. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78301. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78302. * @returns a Float32Array containing matrices data
  78303. */
  78304. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78305. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78306. return mesh._bonesTransformMatrices;
  78307. }
  78308. if (!this._transformMatrices) {
  78309. this.prepare();
  78310. }
  78311. return this._transformMatrices;
  78312. };
  78313. /**
  78314. * Gets the current hosting scene
  78315. * @returns a scene object
  78316. */
  78317. Skeleton.prototype.getScene = function () {
  78318. return this._scene;
  78319. };
  78320. // Methods
  78321. /**
  78322. * Gets a string representing the current skeleton data
  78323. * @param fullDetails defines a boolean indicating if we want a verbose version
  78324. * @returns a string representing the current skeleton data
  78325. */
  78326. Skeleton.prototype.toString = function (fullDetails) {
  78327. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78328. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78329. if (fullDetails) {
  78330. ret += ", Ranges: {";
  78331. var first = true;
  78332. for (var name_1 in this._ranges) {
  78333. if (first) {
  78334. ret += ", ";
  78335. first = false;
  78336. }
  78337. ret += name_1;
  78338. }
  78339. ret += "}";
  78340. }
  78341. return ret;
  78342. };
  78343. /**
  78344. * Get bone's index searching by name
  78345. * @param name defines bone's name to search for
  78346. * @return the indice of the bone. Returns -1 if not found
  78347. */
  78348. Skeleton.prototype.getBoneIndexByName = function (name) {
  78349. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78350. if (this.bones[boneIndex].name === name) {
  78351. return boneIndex;
  78352. }
  78353. }
  78354. return -1;
  78355. };
  78356. /**
  78357. * Creater a new animation range
  78358. * @param name defines the name of the range
  78359. * @param from defines the start key
  78360. * @param to defines the end key
  78361. */
  78362. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78363. // check name not already in use
  78364. if (!this._ranges[name]) {
  78365. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78366. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78367. if (this.bones[i].animations[0]) {
  78368. this.bones[i].animations[0].createRange(name, from, to);
  78369. }
  78370. }
  78371. }
  78372. };
  78373. /**
  78374. * Delete a specific animation range
  78375. * @param name defines the name of the range
  78376. * @param deleteFrames defines if frames must be removed as well
  78377. */
  78378. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78379. if (deleteFrames === void 0) { deleteFrames = true; }
  78380. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78381. if (this.bones[i].animations[0]) {
  78382. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78383. }
  78384. }
  78385. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78386. };
  78387. /**
  78388. * Gets a specific animation range
  78389. * @param name defines the name of the range to look for
  78390. * @returns the requested animation range or null if not found
  78391. */
  78392. Skeleton.prototype.getAnimationRange = function (name) {
  78393. return this._ranges[name];
  78394. };
  78395. /**
  78396. * Gets the list of all animation ranges defined on this skeleton
  78397. * @returns an array
  78398. */
  78399. Skeleton.prototype.getAnimationRanges = function () {
  78400. var animationRanges = [];
  78401. var name;
  78402. var i = 0;
  78403. for (name in this._ranges) {
  78404. animationRanges[i] = this._ranges[name];
  78405. i++;
  78406. }
  78407. return animationRanges;
  78408. };
  78409. /**
  78410. * Copy animation range from a source skeleton.
  78411. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  78412. * @param source defines the source skeleton
  78413. * @param name defines the name of the range to copy
  78414. * @param rescaleAsRequired defines if rescaling must be applied if required
  78415. * @returns true if operation was successful
  78416. */
  78417. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  78418. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78419. if (this._ranges[name] || !source.getAnimationRange(name)) {
  78420. return false;
  78421. }
  78422. var ret = true;
  78423. var frameOffset = this._getHighestAnimationFrame() + 1;
  78424. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  78425. var boneDict = {};
  78426. var sourceBones = source.bones;
  78427. var nBones;
  78428. var i;
  78429. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  78430. boneDict[sourceBones[i].name] = sourceBones[i];
  78431. }
  78432. if (this.bones.length !== sourceBones.length) {
  78433. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  78434. ret = false;
  78435. }
  78436. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  78437. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  78438. var boneName = this.bones[i].name;
  78439. var sourceBone = boneDict[boneName];
  78440. if (sourceBone) {
  78441. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  78442. }
  78443. else {
  78444. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  78445. ret = false;
  78446. }
  78447. }
  78448. // do not call createAnimationRange(), since it also is done to bones, which was already done
  78449. var range = source.getAnimationRange(name);
  78450. if (range) {
  78451. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  78452. }
  78453. return ret;
  78454. };
  78455. /**
  78456. * Forces the skeleton to go to rest pose
  78457. */
  78458. Skeleton.prototype.returnToRest = function () {
  78459. for (var index = 0; index < this.bones.length; index++) {
  78460. this.bones[index].returnToRest();
  78461. }
  78462. };
  78463. Skeleton.prototype._getHighestAnimationFrame = function () {
  78464. var ret = 0;
  78465. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78466. if (this.bones[i].animations[0]) {
  78467. var highest = this.bones[i].animations[0].getHighestFrame();
  78468. if (ret < highest) {
  78469. ret = highest;
  78470. }
  78471. }
  78472. }
  78473. return ret;
  78474. };
  78475. /**
  78476. * Begin a specific animation range
  78477. * @param name defines the name of the range to start
  78478. * @param loop defines if looping must be turned on (false by default)
  78479. * @param speedRatio defines the speed ratio to apply (1 by default)
  78480. * @param onAnimationEnd defines a callback which will be called when animation will end
  78481. * @returns a new animatable
  78482. */
  78483. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  78484. var range = this.getAnimationRange(name);
  78485. if (!range) {
  78486. return null;
  78487. }
  78488. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  78489. };
  78490. /** @ignore */
  78491. Skeleton.prototype._markAsDirty = function () {
  78492. this._isDirty = true;
  78493. };
  78494. /** @ignore */
  78495. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  78496. this._meshesWithPoseMatrix.push(mesh);
  78497. };
  78498. /** @ignore */
  78499. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  78500. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  78501. if (index > -1) {
  78502. this._meshesWithPoseMatrix.splice(index, 1);
  78503. }
  78504. };
  78505. /** @ignore */
  78506. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  78507. this.onBeforeComputeObservable.notifyObservers(this);
  78508. for (var index = 0; index < this.bones.length; index++) {
  78509. var bone = this.bones[index];
  78510. var parentBone = bone.getParent();
  78511. if (parentBone) {
  78512. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  78513. }
  78514. else {
  78515. if (initialSkinMatrix) {
  78516. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  78517. }
  78518. else {
  78519. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  78520. }
  78521. }
  78522. if (bone._index !== -1) {
  78523. var mappedIndex = bone._index === null ? index : bone._index;
  78524. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  78525. }
  78526. }
  78527. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  78528. };
  78529. /**
  78530. * Build all resources required to render a skeleton
  78531. */
  78532. Skeleton.prototype.prepare = function () {
  78533. if (!this._isDirty) {
  78534. return;
  78535. }
  78536. if (this.needInitialSkinMatrix) {
  78537. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  78538. var mesh = this._meshesWithPoseMatrix[index];
  78539. var poseMatrix = mesh.getPoseMatrix();
  78540. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  78541. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78542. }
  78543. if (this._synchronizedWithMesh !== mesh) {
  78544. this._synchronizedWithMesh = mesh;
  78545. // Prepare bones
  78546. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  78547. var bone = this.bones[boneIndex];
  78548. if (!bone.getParent()) {
  78549. var matrix = bone.getBaseMatrix();
  78550. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  78551. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  78552. }
  78553. }
  78554. }
  78555. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  78556. }
  78557. }
  78558. else {
  78559. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  78560. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78561. }
  78562. this._computeTransformMatrices(this._transformMatrices, null);
  78563. }
  78564. this._isDirty = false;
  78565. this._scene._activeBones.addCount(this.bones.length, false);
  78566. };
  78567. /**
  78568. * Gets the list of animatables currently running for this skeleton
  78569. * @returns an array of animatables
  78570. */
  78571. Skeleton.prototype.getAnimatables = function () {
  78572. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78573. this._animatables = [];
  78574. for (var index = 0; index < this.bones.length; index++) {
  78575. this._animatables.push(this.bones[index]);
  78576. }
  78577. }
  78578. return this._animatables;
  78579. };
  78580. /**
  78581. * Clone the current skeleton
  78582. * @param name defines the name of the new skeleton
  78583. * @param id defines the id of the enw skeleton
  78584. * @returns the new skeleton
  78585. */
  78586. Skeleton.prototype.clone = function (name, id) {
  78587. var result = new Skeleton(name, id || name, this._scene);
  78588. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78589. for (var index = 0; index < this.bones.length; index++) {
  78590. var source = this.bones[index];
  78591. var parentBone = null;
  78592. var parent_1 = source.getParent();
  78593. if (parent_1) {
  78594. var parentIndex = this.bones.indexOf(parent_1);
  78595. parentBone = result.bones[parentIndex];
  78596. }
  78597. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78598. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78599. }
  78600. if (this._ranges) {
  78601. result._ranges = {};
  78602. for (var rangeName in this._ranges) {
  78603. var range = this._ranges[rangeName];
  78604. if (range) {
  78605. result._ranges[rangeName] = range.clone();
  78606. }
  78607. }
  78608. }
  78609. this._isDirty = true;
  78610. return result;
  78611. };
  78612. /**
  78613. * Enable animation blending for this skeleton
  78614. * @param blendingSpeed defines the blending speed to apply
  78615. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  78616. */
  78617. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78618. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78619. this.bones.forEach(function (bone) {
  78620. bone.animations.forEach(function (animation) {
  78621. animation.enableBlending = true;
  78622. animation.blendingSpeed = blendingSpeed;
  78623. });
  78624. });
  78625. };
  78626. /**
  78627. * Releases all resources associated with the current skeleton
  78628. */
  78629. Skeleton.prototype.dispose = function () {
  78630. this._meshesWithPoseMatrix = [];
  78631. // Animations
  78632. this.getScene().stopAnimation(this);
  78633. // Remove from scene
  78634. this.getScene().removeSkeleton(this);
  78635. };
  78636. /**
  78637. * Serialize the skeleton in a JSON object
  78638. * @returns a JSON object
  78639. */
  78640. Skeleton.prototype.serialize = function () {
  78641. var serializationObject = {};
  78642. serializationObject.name = this.name;
  78643. serializationObject.id = this.id;
  78644. if (this.dimensionsAtRest) {
  78645. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78646. }
  78647. serializationObject.bones = [];
  78648. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78649. for (var index = 0; index < this.bones.length; index++) {
  78650. var bone = this.bones[index];
  78651. var parent_2 = bone.getParent();
  78652. var serializedBone = {
  78653. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78654. name: bone.name,
  78655. matrix: bone.getBaseMatrix().toArray(),
  78656. rest: bone.getRestPose().toArray()
  78657. };
  78658. serializationObject.bones.push(serializedBone);
  78659. if (bone.length) {
  78660. serializedBone.length = bone.length;
  78661. }
  78662. if (bone.animations && bone.animations.length > 0) {
  78663. serializedBone.animation = bone.animations[0].serialize();
  78664. }
  78665. serializationObject.ranges = [];
  78666. for (var name in this._ranges) {
  78667. var source = this._ranges[name];
  78668. if (!source) {
  78669. continue;
  78670. }
  78671. var range = {};
  78672. range.name = name;
  78673. range.from = source.from;
  78674. range.to = source.to;
  78675. serializationObject.ranges.push(range);
  78676. }
  78677. }
  78678. return serializationObject;
  78679. };
  78680. /**
  78681. * Creates a new skeleton from serialized data
  78682. * @param parsedSkeleton defines the serialized data
  78683. * @param scene defines the hosting scene
  78684. * @returns a new skeleton
  78685. */
  78686. Skeleton.Parse = function (parsedSkeleton, scene) {
  78687. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78688. if (parsedSkeleton.dimensionsAtRest) {
  78689. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78690. }
  78691. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78692. var index;
  78693. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78694. var parsedBone = parsedSkeleton.bones[index];
  78695. var parentBone = null;
  78696. if (parsedBone.parentBoneIndex > -1) {
  78697. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78698. }
  78699. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78700. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78701. if (parsedBone.length) {
  78702. bone.length = parsedBone.length;
  78703. }
  78704. if (parsedBone.animation) {
  78705. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78706. }
  78707. }
  78708. // placed after bones, so createAnimationRange can cascade down
  78709. if (parsedSkeleton.ranges) {
  78710. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78711. var data = parsedSkeleton.ranges[index];
  78712. skeleton.createAnimationRange(data.name, data.from, data.to);
  78713. }
  78714. }
  78715. return skeleton;
  78716. };
  78717. /**
  78718. * Compute all node absolute transforms
  78719. * @param forceUpdate defines if computation must be done even if cache is up to date
  78720. */
  78721. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78722. if (forceUpdate === void 0) { forceUpdate = false; }
  78723. var renderId = this._scene.getRenderId();
  78724. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78725. this.bones[0].computeAbsoluteTransforms();
  78726. this._lastAbsoluteTransformsUpdateId = renderId;
  78727. }
  78728. };
  78729. /**
  78730. * Gets the root pose matrix
  78731. * @returns a matrix
  78732. */
  78733. Skeleton.prototype.getPoseMatrix = function () {
  78734. var poseMatrix = null;
  78735. if (this._meshesWithPoseMatrix.length > 0) {
  78736. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78737. }
  78738. return poseMatrix;
  78739. };
  78740. /**
  78741. * Sorts bones per internal index
  78742. */
  78743. Skeleton.prototype.sortBones = function () {
  78744. var bones = new Array();
  78745. var visited = new Array(this.bones.length);
  78746. for (var index = 0; index < this.bones.length; index++) {
  78747. this._sortBones(index, bones, visited);
  78748. }
  78749. this.bones = bones;
  78750. };
  78751. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78752. if (visited[index]) {
  78753. return;
  78754. }
  78755. visited[index] = true;
  78756. var bone = this.bones[index];
  78757. if (bone._index === undefined) {
  78758. bone._index = index;
  78759. }
  78760. var parentBone = bone.getParent();
  78761. if (parentBone) {
  78762. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78763. }
  78764. bones.push(bone);
  78765. };
  78766. return Skeleton;
  78767. }());
  78768. BABYLON.Skeleton = Skeleton;
  78769. })(BABYLON || (BABYLON = {}));
  78770. //# sourceMappingURL=babylon.skeleton.js.map
  78771. var BABYLON;
  78772. (function (BABYLON) {
  78773. var SphericalPolynomial = /** @class */ (function () {
  78774. function SphericalPolynomial() {
  78775. this.x = BABYLON.Vector3.Zero();
  78776. this.y = BABYLON.Vector3.Zero();
  78777. this.z = BABYLON.Vector3.Zero();
  78778. this.xx = BABYLON.Vector3.Zero();
  78779. this.yy = BABYLON.Vector3.Zero();
  78780. this.zz = BABYLON.Vector3.Zero();
  78781. this.xy = BABYLON.Vector3.Zero();
  78782. this.yz = BABYLON.Vector3.Zero();
  78783. this.zx = BABYLON.Vector3.Zero();
  78784. }
  78785. SphericalPolynomial.prototype.addAmbient = function (color) {
  78786. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78787. this.xx = this.xx.add(colorVector);
  78788. this.yy = this.yy.add(colorVector);
  78789. this.zz = this.zz.add(colorVector);
  78790. };
  78791. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78792. var result = new SphericalPolynomial();
  78793. result.x = harmonics.L11.scale(1.02333);
  78794. result.y = harmonics.L1_1.scale(1.02333);
  78795. result.z = harmonics.L10.scale(1.02333);
  78796. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78797. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78798. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78799. result.yz = harmonics.L2_1.scale(0.858086);
  78800. result.zx = harmonics.L21.scale(0.858086);
  78801. result.xy = harmonics.L2_2.scale(0.858086);
  78802. result.scale(1.0 / Math.PI);
  78803. return result;
  78804. };
  78805. SphericalPolynomial.prototype.scale = function (scale) {
  78806. this.x = this.x.scale(scale);
  78807. this.y = this.y.scale(scale);
  78808. this.z = this.z.scale(scale);
  78809. this.xx = this.xx.scale(scale);
  78810. this.yy = this.yy.scale(scale);
  78811. this.zz = this.zz.scale(scale);
  78812. this.yz = this.yz.scale(scale);
  78813. this.zx = this.zx.scale(scale);
  78814. this.xy = this.xy.scale(scale);
  78815. };
  78816. return SphericalPolynomial;
  78817. }());
  78818. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78819. var SphericalHarmonics = /** @class */ (function () {
  78820. function SphericalHarmonics() {
  78821. this.L00 = BABYLON.Vector3.Zero();
  78822. this.L1_1 = BABYLON.Vector3.Zero();
  78823. this.L10 = BABYLON.Vector3.Zero();
  78824. this.L11 = BABYLON.Vector3.Zero();
  78825. this.L2_2 = BABYLON.Vector3.Zero();
  78826. this.L2_1 = BABYLON.Vector3.Zero();
  78827. this.L20 = BABYLON.Vector3.Zero();
  78828. this.L21 = BABYLON.Vector3.Zero();
  78829. this.L22 = BABYLON.Vector3.Zero();
  78830. }
  78831. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78832. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78833. var c = colorVector.scale(deltaSolidAngle);
  78834. this.L00 = this.L00.add(c.scale(0.282095));
  78835. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78836. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78837. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78838. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78839. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78840. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78841. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78842. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78843. };
  78844. SphericalHarmonics.prototype.scale = function (scale) {
  78845. this.L00 = this.L00.scale(scale);
  78846. this.L1_1 = this.L1_1.scale(scale);
  78847. this.L10 = this.L10.scale(scale);
  78848. this.L11 = this.L11.scale(scale);
  78849. this.L2_2 = this.L2_2.scale(scale);
  78850. this.L2_1 = this.L2_1.scale(scale);
  78851. this.L20 = this.L20.scale(scale);
  78852. this.L21 = this.L21.scale(scale);
  78853. this.L22 = this.L22.scale(scale);
  78854. };
  78855. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78856. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78857. //
  78858. // E_lm = A_l * L_lm
  78859. //
  78860. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78861. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78862. // the scaling factors are given in equation 9.
  78863. // Constant (Band 0)
  78864. this.L00 = this.L00.scale(3.141593);
  78865. // Linear (Band 1)
  78866. this.L1_1 = this.L1_1.scale(2.094395);
  78867. this.L10 = this.L10.scale(2.094395);
  78868. this.L11 = this.L11.scale(2.094395);
  78869. // Quadratic (Band 2)
  78870. this.L2_2 = this.L2_2.scale(0.785398);
  78871. this.L2_1 = this.L2_1.scale(0.785398);
  78872. this.L20 = this.L20.scale(0.785398);
  78873. this.L21 = this.L21.scale(0.785398);
  78874. this.L22 = this.L22.scale(0.785398);
  78875. };
  78876. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78877. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78878. // L = (1/pi) * E * rho
  78879. //
  78880. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78881. this.scale(1.0 / Math.PI);
  78882. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78883. // (The pixel shader must apply albedo after texture fetches, etc).
  78884. };
  78885. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78886. var result = new SphericalHarmonics();
  78887. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78888. result.L1_1 = polynomial.y.scale(0.977204);
  78889. result.L10 = polynomial.z.scale(0.977204);
  78890. result.L11 = polynomial.x.scale(0.977204);
  78891. result.L2_2 = polynomial.xy.scale(1.16538);
  78892. result.L2_1 = polynomial.yz.scale(1.16538);
  78893. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  78894. result.L21 = polynomial.zx.scale(1.16538);
  78895. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  78896. result.scale(Math.PI);
  78897. return result;
  78898. };
  78899. return SphericalHarmonics;
  78900. }());
  78901. BABYLON.SphericalHarmonics = SphericalHarmonics;
  78902. })(BABYLON || (BABYLON = {}));
  78903. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78904. var BABYLON;
  78905. (function (BABYLON) {
  78906. var FileFaceOrientation = /** @class */ (function () {
  78907. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78908. this.name = name;
  78909. this.worldAxisForNormal = worldAxisForNormal;
  78910. this.worldAxisForFileX = worldAxisForFileX;
  78911. this.worldAxisForFileY = worldAxisForFileY;
  78912. }
  78913. return FileFaceOrientation;
  78914. }());
  78915. ;
  78916. /**
  78917. * Helper class dealing with the extraction of spherical polynomial dataArray
  78918. * from a cube map.
  78919. */
  78920. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78921. function CubeMapToSphericalPolynomialTools() {
  78922. }
  78923. /**
  78924. * Converts a texture to the according Spherical Polynomial data.
  78925. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78926. *
  78927. * @param texture The texture to extract the information from.
  78928. * @return The Spherical Polynomial data.
  78929. */
  78930. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78931. if (!texture.isCube) {
  78932. // Only supports cube Textures currently.
  78933. return null;
  78934. }
  78935. var size = texture.getSize().width;
  78936. var right = texture.readPixels(0);
  78937. var left = texture.readPixels(1);
  78938. var up;
  78939. var down;
  78940. if (texture.isRenderTarget) {
  78941. up = texture.readPixels(3);
  78942. down = texture.readPixels(2);
  78943. }
  78944. else {
  78945. up = texture.readPixels(2);
  78946. down = texture.readPixels(3);
  78947. }
  78948. var front = texture.readPixels(4);
  78949. var back = texture.readPixels(5);
  78950. var gammaSpace = texture.gammaSpace;
  78951. // Always read as RGBA.
  78952. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78953. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78954. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78955. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78956. }
  78957. var cubeInfo = {
  78958. size: size,
  78959. right: right,
  78960. left: left,
  78961. up: up,
  78962. down: down,
  78963. front: front,
  78964. back: back,
  78965. format: format,
  78966. type: type,
  78967. gammaSpace: gammaSpace,
  78968. };
  78969. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78970. };
  78971. /**
  78972. * Converts a cubemap to the according Spherical Polynomial data.
  78973. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78974. *
  78975. * @param cubeInfo The Cube map to extract the information from.
  78976. * @return The Spherical Polynomial data.
  78977. */
  78978. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78979. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78980. var totalSolidAngle = 0.0;
  78981. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78982. var du = 2.0 / cubeInfo.size;
  78983. var dv = du;
  78984. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78985. var minUV = du * 0.5 - 1.0;
  78986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78987. var fileFace = this.FileFaces[faceIndex];
  78988. var dataArray = cubeInfo[fileFace.name];
  78989. var v = minUV;
  78990. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78991. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78992. // Because SP is still linear, so summation is fine in that basis.
  78993. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78994. for (var y = 0; y < cubeInfo.size; y++) {
  78995. var u = minUV;
  78996. for (var x = 0; x < cubeInfo.size; x++) {
  78997. // World direction (not normalised)
  78998. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78999. worldDirection.normalize();
  79000. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79001. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79002. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79003. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79004. // Handle Integer types.
  79005. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79006. r /= 255;
  79007. g /= 255;
  79008. b /= 255;
  79009. }
  79010. // Handle Gamma space textures.
  79011. if (cubeInfo.gammaSpace) {
  79012. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79013. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79014. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79015. }
  79016. var color = new BABYLON.Color3(r, g, b);
  79017. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79018. totalSolidAngle += deltaSolidAngle;
  79019. u += du;
  79020. }
  79021. v += dv;
  79022. }
  79023. }
  79024. // Solid angle for entire sphere is 4*pi
  79025. var sphereSolidAngle = 4.0 * Math.PI;
  79026. // Adjust the solid angle to allow for how many faces we processed.
  79027. var facesProcessed = 6.0;
  79028. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79029. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79030. // This is needed because the numerical integration over the cube uses a
  79031. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79032. // and also to compensate for accumulative error due to float precision in the summation.
  79033. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79034. sphericalHarmonics.scale(correctionFactor);
  79035. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79036. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79037. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79038. };
  79039. CubeMapToSphericalPolynomialTools.FileFaces = [
  79040. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79041. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79042. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79043. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79044. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79045. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79046. ];
  79047. return CubeMapToSphericalPolynomialTools;
  79048. }());
  79049. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79050. })(BABYLON || (BABYLON = {}));
  79051. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79052. var BABYLON;
  79053. (function (BABYLON) {
  79054. /**
  79055. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79056. */
  79057. var PanoramaToCubeMapTools = /** @class */ (function () {
  79058. function PanoramaToCubeMapTools() {
  79059. }
  79060. /**
  79061. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79062. *
  79063. * @param float32Array The source data.
  79064. * @param inputWidth The width of the input panorama.
  79065. * @param inputhHeight The height of the input panorama.
  79066. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79067. * @return The cubemap data
  79068. */
  79069. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79070. if (!float32Array) {
  79071. throw "ConvertPanoramaToCubemap: input cannot be null";
  79072. }
  79073. if (float32Array.length != inputWidth * inputHeight * 3) {
  79074. throw "ConvertPanoramaToCubemap: input size is wrong";
  79075. }
  79076. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79077. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79078. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79079. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79080. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79081. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79082. return {
  79083. front: textureFront,
  79084. back: textureBack,
  79085. left: textureLeft,
  79086. right: textureRight,
  79087. up: textureUp,
  79088. down: textureDown,
  79089. size: size,
  79090. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79091. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79092. gammaSpace: false,
  79093. };
  79094. };
  79095. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79096. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79097. var textureArray = new Float32Array(buffer);
  79098. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79099. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79100. var dy = 1 / texSize;
  79101. var fy = 0;
  79102. for (var y = 0; y < texSize; y++) {
  79103. var xv1 = faceData[0];
  79104. var xv2 = faceData[2];
  79105. for (var x = 0; x < texSize; x++) {
  79106. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79107. v.normalize();
  79108. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79109. // 3 channels per pixels
  79110. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79111. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79112. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79113. xv1 = xv1.add(rotDX1);
  79114. xv2 = xv2.add(rotDX2);
  79115. }
  79116. fy += dy;
  79117. }
  79118. return textureArray;
  79119. };
  79120. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79121. var theta = Math.atan2(vDir.z, vDir.x);
  79122. var phi = Math.acos(vDir.y);
  79123. while (theta < -Math.PI)
  79124. theta += 2 * Math.PI;
  79125. while (theta > Math.PI)
  79126. theta -= 2 * Math.PI;
  79127. var dx = theta / Math.PI;
  79128. var dy = phi / Math.PI;
  79129. // recenter.
  79130. dx = dx * 0.5 + 0.5;
  79131. var px = Math.round(dx * inputWidth);
  79132. if (px < 0)
  79133. px = 0;
  79134. else if (px >= inputWidth)
  79135. px = inputWidth - 1;
  79136. var py = Math.round(dy * inputHeight);
  79137. if (py < 0)
  79138. py = 0;
  79139. else if (py >= inputHeight)
  79140. py = inputHeight - 1;
  79141. var inputY = (inputHeight - py - 1);
  79142. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79143. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79144. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79145. return {
  79146. r: r,
  79147. g: g,
  79148. b: b
  79149. };
  79150. };
  79151. PanoramaToCubeMapTools.FACE_FRONT = [
  79152. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79153. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79154. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79155. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79156. ];
  79157. PanoramaToCubeMapTools.FACE_BACK = [
  79158. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79159. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79160. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79161. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79162. ];
  79163. PanoramaToCubeMapTools.FACE_RIGHT = [
  79164. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79165. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79166. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79167. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79168. ];
  79169. PanoramaToCubeMapTools.FACE_LEFT = [
  79170. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79171. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79172. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79173. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79174. ];
  79175. PanoramaToCubeMapTools.FACE_DOWN = [
  79176. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79177. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79178. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79179. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79180. ];
  79181. PanoramaToCubeMapTools.FACE_UP = [
  79182. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79183. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79184. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79185. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79186. ];
  79187. return PanoramaToCubeMapTools;
  79188. }());
  79189. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79190. })(BABYLON || (BABYLON = {}));
  79191. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79192. var BABYLON;
  79193. (function (BABYLON) {
  79194. ;
  79195. /**
  79196. * This groups tools to convert HDR texture to native colors array.
  79197. */
  79198. var HDRTools = /** @class */ (function () {
  79199. function HDRTools() {
  79200. }
  79201. HDRTools.Ldexp = function (mantissa, exponent) {
  79202. if (exponent > 1023) {
  79203. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79204. }
  79205. if (exponent < -1074) {
  79206. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79207. }
  79208. return mantissa * Math.pow(2, exponent);
  79209. };
  79210. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79211. if (exponent > 0) { /*nonzero pixel*/
  79212. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79213. float32array[index + 0] = red * exponent;
  79214. float32array[index + 1] = green * exponent;
  79215. float32array[index + 2] = blue * exponent;
  79216. }
  79217. else {
  79218. float32array[index + 0] = 0;
  79219. float32array[index + 1] = 0;
  79220. float32array[index + 2] = 0;
  79221. }
  79222. };
  79223. HDRTools.readStringLine = function (uint8array, startIndex) {
  79224. var line = "";
  79225. var character = "";
  79226. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79227. character = String.fromCharCode(uint8array[i]);
  79228. if (character == "\n") {
  79229. break;
  79230. }
  79231. line += character;
  79232. }
  79233. return line;
  79234. };
  79235. /**
  79236. * Reads header information from an RGBE texture stored in a native array.
  79237. * More information on this format are available here:
  79238. * https://en.wikipedia.org/wiki/RGBE_image_format
  79239. *
  79240. * @param uint8array The binary file stored in native array.
  79241. * @return The header information.
  79242. */
  79243. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79244. var height = 0;
  79245. var width = 0;
  79246. var line = this.readStringLine(uint8array, 0);
  79247. if (line[0] != '#' || line[1] != '?') {
  79248. throw "Bad HDR Format.";
  79249. }
  79250. var endOfHeader = false;
  79251. var findFormat = false;
  79252. var lineIndex = 0;
  79253. do {
  79254. lineIndex += (line.length + 1);
  79255. line = this.readStringLine(uint8array, lineIndex);
  79256. if (line == "FORMAT=32-bit_rle_rgbe") {
  79257. findFormat = true;
  79258. }
  79259. else if (line.length == 0) {
  79260. endOfHeader = true;
  79261. }
  79262. } while (!endOfHeader);
  79263. if (!findFormat) {
  79264. throw "HDR Bad header format, unsupported FORMAT";
  79265. }
  79266. lineIndex += (line.length + 1);
  79267. line = this.readStringLine(uint8array, lineIndex);
  79268. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79269. var match = sizeRegexp.exec(line);
  79270. // TODO. Support +Y and -X if needed.
  79271. if (!match || match.length < 3) {
  79272. throw "HDR Bad header format, no size";
  79273. }
  79274. width = parseInt(match[2]);
  79275. height = parseInt(match[1]);
  79276. if (width < 8 || width > 0x7fff) {
  79277. throw "HDR Bad header format, unsupported size";
  79278. }
  79279. lineIndex += (line.length + 1);
  79280. return {
  79281. height: height,
  79282. width: width,
  79283. dataPosition: lineIndex
  79284. };
  79285. };
  79286. /**
  79287. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79288. * This RGBE texture needs to store the information as a panorama.
  79289. *
  79290. * More information on this format are available here:
  79291. * https://en.wikipedia.org/wiki/RGBE_image_format
  79292. *
  79293. * @param buffer The binary file stored in an array buffer.
  79294. * @param size The expected size of the extracted cubemap.
  79295. * @return The Cube Map information.
  79296. */
  79297. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79298. var uint8array = new Uint8Array(buffer);
  79299. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79300. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79301. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79302. return cubeMapData;
  79303. };
  79304. /**
  79305. * Returns the pixels data extracted from an RGBE texture.
  79306. * This pixels will be stored left to right up to down in the R G B order in one array.
  79307. *
  79308. * More information on this format are available here:
  79309. * https://en.wikipedia.org/wiki/RGBE_image_format
  79310. *
  79311. * @param uint8array The binary file stored in an array buffer.
  79312. * @param hdrInfo The header information of the file.
  79313. * @return The pixels data in RGB right to left up to down order.
  79314. */
  79315. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79316. // Keep for multi format supports.
  79317. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79318. };
  79319. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79320. var num_scanlines = hdrInfo.height;
  79321. var scanline_width = hdrInfo.width;
  79322. var a, b, c, d, count;
  79323. var dataIndex = hdrInfo.dataPosition;
  79324. var index = 0, endIndex = 0, i = 0;
  79325. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79326. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79327. // 3 channels of 4 bytes per pixel in float.
  79328. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79329. var resultArray = new Float32Array(resultBuffer);
  79330. // read in each successive scanline
  79331. while (num_scanlines > 0) {
  79332. a = uint8array[dataIndex++];
  79333. b = uint8array[dataIndex++];
  79334. c = uint8array[dataIndex++];
  79335. d = uint8array[dataIndex++];
  79336. if (a != 2 || b != 2 || (c & 0x80)) {
  79337. // this file is not run length encoded
  79338. throw "HDR Bad header format, not RLE";
  79339. }
  79340. if (((c << 8) | d) != scanline_width) {
  79341. throw "HDR Bad header format, wrong scan line width";
  79342. }
  79343. index = 0;
  79344. // read each of the four channels for the scanline into the buffer
  79345. for (i = 0; i < 4; i++) {
  79346. endIndex = (i + 1) * scanline_width;
  79347. while (index < endIndex) {
  79348. a = uint8array[dataIndex++];
  79349. b = uint8array[dataIndex++];
  79350. if (a > 128) {
  79351. // a run of the same value
  79352. count = a - 128;
  79353. if ((count == 0) || (count > endIndex - index)) {
  79354. throw "HDR Bad Format, bad scanline data (run)";
  79355. }
  79356. while (count-- > 0) {
  79357. scanLineArray[index++] = b;
  79358. }
  79359. }
  79360. else {
  79361. // a non-run
  79362. count = a;
  79363. if ((count == 0) || (count > endIndex - index)) {
  79364. throw "HDR Bad Format, bad scanline data (non-run)";
  79365. }
  79366. scanLineArray[index++] = b;
  79367. if (--count > 0) {
  79368. for (var j = 0; j < count; j++) {
  79369. scanLineArray[index++] = uint8array[dataIndex++];
  79370. }
  79371. }
  79372. }
  79373. }
  79374. }
  79375. // now convert data from buffer into floats
  79376. for (i = 0; i < scanline_width; i++) {
  79377. a = scanLineArray[i];
  79378. b = scanLineArray[i + scanline_width];
  79379. c = scanLineArray[i + 2 * scanline_width];
  79380. d = scanLineArray[i + 3 * scanline_width];
  79381. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79382. }
  79383. num_scanlines--;
  79384. }
  79385. return resultArray;
  79386. };
  79387. return HDRTools;
  79388. }());
  79389. BABYLON.HDRTools = HDRTools;
  79390. })(BABYLON || (BABYLON = {}));
  79391. //# sourceMappingURL=babylon.hdr.js.map
  79392. var BABYLON;
  79393. (function (BABYLON) {
  79394. /**
  79395. * This represents a texture coming from an HDR input.
  79396. *
  79397. * The only supported format is currently panorama picture stored in RGBE format.
  79398. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79399. */
  79400. var HDRCubeTexture = /** @class */ (function (_super) {
  79401. __extends(HDRCubeTexture, _super);
  79402. /**
  79403. * Instantiates an HDRTexture from the following parameters.
  79404. *
  79405. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  79406. * @param scene The scene the texture will be used in
  79407. * @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.
  79408. * @param noMipmap Forces to not generate the mipmap if true
  79409. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  79410. * @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)
  79411. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  79412. */
  79413. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  79414. if (noMipmap === void 0) { noMipmap = false; }
  79415. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79416. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79417. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79418. if (onLoad === void 0) { onLoad = null; }
  79419. if (onError === void 0) { onError = null; }
  79420. var _this = _super.call(this, scene) || this;
  79421. _this._useInGammaSpace = false;
  79422. _this._generateHarmonics = true;
  79423. _this._isBABYLONPreprocessed = false;
  79424. _this._onLoad = null;
  79425. _this._onError = null;
  79426. /**
  79427. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  79428. */
  79429. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  79430. /**
  79431. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  79432. * This is usefull at run time to apply the good shader.
  79433. */
  79434. _this.isPMREM = false;
  79435. _this._isBlocking = true;
  79436. _this._rotationY = 0;
  79437. /**
  79438. * Gets or sets the center of the bounding box associated with the cube texture
  79439. * It must define where the camera used to render the texture was set
  79440. */
  79441. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  79442. if (!url) {
  79443. return _this;
  79444. }
  79445. _this.name = url;
  79446. _this.url = url;
  79447. _this.hasAlpha = false;
  79448. _this.isCube = true;
  79449. _this._textureMatrix = BABYLON.Matrix.Identity();
  79450. _this._onLoad = onLoad;
  79451. _this._onError = onError;
  79452. _this.gammaSpace = false;
  79453. var caps = scene.getEngine().getCaps();
  79454. if (size) {
  79455. _this._isBABYLONPreprocessed = false;
  79456. _this._noMipmap = noMipmap;
  79457. _this._size = size;
  79458. _this._useInGammaSpace = useInGammaSpace;
  79459. _this._usePMREMGenerator = usePMREMGenerator &&
  79460. caps.textureLOD &&
  79461. caps.textureFloat &&
  79462. !_this._useInGammaSpace;
  79463. }
  79464. else {
  79465. _this._isBABYLONPreprocessed = true;
  79466. _this._noMipmap = false;
  79467. _this._useInGammaSpace = false;
  79468. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  79469. !_this._useInGammaSpace;
  79470. }
  79471. _this.isPMREM = _this._usePMREMGenerator;
  79472. _this._texture = _this._getFromCache(url, _this._noMipmap);
  79473. if (!_this._texture) {
  79474. if (!scene.useDelayedTextureLoading) {
  79475. _this.loadTexture();
  79476. }
  79477. else {
  79478. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79479. }
  79480. }
  79481. return _this;
  79482. }
  79483. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  79484. /**
  79485. * Gets wether or not the texture is blocking during loading.
  79486. */
  79487. get: function () {
  79488. return this._isBlocking;
  79489. },
  79490. /**
  79491. * Sets wether or not the texture is blocking during loading.
  79492. */
  79493. set: function (value) {
  79494. this._isBlocking = value;
  79495. },
  79496. enumerable: true,
  79497. configurable: true
  79498. });
  79499. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  79500. /**
  79501. * Gets texture matrix rotation angle around Y axis radians.
  79502. */
  79503. get: function () {
  79504. return this._rotationY;
  79505. },
  79506. /**
  79507. * Sets texture matrix rotation angle around Y axis in radians.
  79508. */
  79509. set: function (value) {
  79510. this._rotationY = value;
  79511. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  79512. },
  79513. enumerable: true,
  79514. configurable: true
  79515. });
  79516. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  79517. get: function () {
  79518. return this._boundingBoxSize;
  79519. },
  79520. /**
  79521. * Gets or sets the size of the bounding box associated with the cube texture
  79522. * When defined, the cubemap will switch to local mode
  79523. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  79524. * @example https://www.babylonjs-playground.com/#RNASML
  79525. */
  79526. set: function (value) {
  79527. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  79528. return;
  79529. }
  79530. this._boundingBoxSize = value;
  79531. var scene = this.getScene();
  79532. if (scene) {
  79533. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  79534. }
  79535. },
  79536. enumerable: true,
  79537. configurable: true
  79538. });
  79539. /**
  79540. * Occurs when the file is a preprocessed .babylon.hdr file.
  79541. */
  79542. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  79543. var _this = this;
  79544. var mipLevels = 0;
  79545. var floatArrayView = null;
  79546. var scene = this.getScene();
  79547. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  79548. var mips = new Array();
  79549. if (!floatArrayView) {
  79550. return mips;
  79551. }
  79552. var startIndex = 30;
  79553. for (var level = 0; level < mipLevels; level++) {
  79554. mips.push([]);
  79555. // Fill each pixel of the mip level.
  79556. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  79557. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79558. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  79559. mips[level].push(faceData);
  79560. startIndex += faceSize;
  79561. }
  79562. }
  79563. return mips;
  79564. } : null;
  79565. var callback = function (buffer) {
  79566. var scene = _this.getScene();
  79567. if (!scene) {
  79568. return null;
  79569. }
  79570. // Create Native Array Views
  79571. var intArrayView = new Int32Array(buffer);
  79572. floatArrayView = new Float32Array(buffer);
  79573. // Fill header.
  79574. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  79575. _this._size = intArrayView[1]; // CubeMap max mip face size.
  79576. // Update Texture Information.
  79577. if (!_this._texture) {
  79578. return null;
  79579. }
  79580. _this._texture.updateSize(_this._size, _this._size);
  79581. // Fill polynomial information.
  79582. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  79583. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  79584. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  79585. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  79586. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  79587. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  79588. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  79589. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  79590. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  79591. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  79592. _this.sphericalPolynomial = sphericalPolynomial;
  79593. // Fill pixel data.
  79594. mipLevels = intArrayView[29]; // Number of mip levels.
  79595. var startIndex = 30;
  79596. var data = [];
  79597. var faceSize = Math.pow(_this._size, 2) * 3;
  79598. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79599. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79600. startIndex += faceSize;
  79601. }
  79602. var results = [];
  79603. var byteArray = null;
  79604. // Push each faces.
  79605. for (var k = 0; k < 6; k++) {
  79606. var dataFace = null;
  79607. // To be deprecated.
  79608. if (version === 1) {
  79609. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79610. dataFace = data[j];
  79611. }
  79612. // If special cases.
  79613. if (!mipmapGenerator && dataFace) {
  79614. if (!scene.getEngine().getCaps().textureFloat) {
  79615. // 3 channels of 1 bytes per pixel in bytes.
  79616. var byteBuffer = new ArrayBuffer(faceSize);
  79617. byteArray = new Uint8Array(byteBuffer);
  79618. }
  79619. for (var i = 0; i < _this._size * _this._size; i++) {
  79620. // Put in gamma space if requested.
  79621. if (_this._useInGammaSpace) {
  79622. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79623. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79624. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79625. }
  79626. // Convert to int texture for fallback.
  79627. if (byteArray) {
  79628. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79629. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79630. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79631. // May use luminance instead if the result is not accurate.
  79632. var max = Math.max(Math.max(r, g), b);
  79633. if (max > 255) {
  79634. var scale = 255 / max;
  79635. r *= scale;
  79636. g *= scale;
  79637. b *= scale;
  79638. }
  79639. byteArray[(i * 3) + 0] = r;
  79640. byteArray[(i * 3) + 1] = g;
  79641. byteArray[(i * 3) + 2] = b;
  79642. }
  79643. }
  79644. }
  79645. // Fill the array accordingly.
  79646. if (byteArray) {
  79647. results.push(byteArray);
  79648. }
  79649. else {
  79650. results.push(dataFace);
  79651. }
  79652. }
  79653. return results;
  79654. };
  79655. if (scene) {
  79656. 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);
  79657. }
  79658. };
  79659. /**
  79660. * Occurs when the file is raw .hdr file.
  79661. */
  79662. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79663. var _this = this;
  79664. var callback = function (buffer) {
  79665. var scene = _this.getScene();
  79666. if (!scene) {
  79667. return null;
  79668. }
  79669. // Extract the raw linear data.
  79670. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79671. // Generate harmonics if needed.
  79672. if (_this._generateHarmonics) {
  79673. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79674. _this.sphericalPolynomial = sphericalPolynomial;
  79675. }
  79676. var results = [];
  79677. var byteArray = null;
  79678. // Push each faces.
  79679. for (var j = 0; j < 6; j++) {
  79680. // Create uintarray fallback.
  79681. if (!scene.getEngine().getCaps().textureFloat) {
  79682. // 3 channels of 1 bytes per pixel in bytes.
  79683. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79684. byteArray = new Uint8Array(byteBuffer);
  79685. }
  79686. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79687. // If special cases.
  79688. if (_this._useInGammaSpace || byteArray) {
  79689. for (var i = 0; i < _this._size * _this._size; i++) {
  79690. // Put in gamma space if requested.
  79691. if (_this._useInGammaSpace) {
  79692. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79693. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79694. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79695. }
  79696. // Convert to int texture for fallback.
  79697. if (byteArray) {
  79698. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79699. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79700. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79701. // May use luminance instead if the result is not accurate.
  79702. var max = Math.max(Math.max(r, g), b);
  79703. if (max > 255) {
  79704. var scale = 255 / max;
  79705. r *= scale;
  79706. g *= scale;
  79707. b *= scale;
  79708. }
  79709. byteArray[(i * 3) + 0] = r;
  79710. byteArray[(i * 3) + 1] = g;
  79711. byteArray[(i * 3) + 2] = b;
  79712. }
  79713. }
  79714. }
  79715. if (byteArray) {
  79716. results.push(byteArray);
  79717. }
  79718. else {
  79719. results.push(dataFace);
  79720. }
  79721. }
  79722. return results;
  79723. };
  79724. var mipmapGenerator = null;
  79725. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79726. // if (!this._noMipmap &&
  79727. // this._usePMREMGenerator) {
  79728. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79729. // // Custom setup of the generator matching with the PBR shader values.
  79730. // var generator = new BABYLON.PMREMGenerator(data,
  79731. // this._size,
  79732. // this._size,
  79733. // 0,
  79734. // 3,
  79735. // this.getScene().getEngine().getCaps().textureFloat,
  79736. // 2048,
  79737. // 0.25,
  79738. // false,
  79739. // true);
  79740. // return generator.filterCubeMap();
  79741. // };
  79742. // }
  79743. var scene = this.getScene();
  79744. if (scene) {
  79745. 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);
  79746. }
  79747. };
  79748. /**
  79749. * Starts the loading process of the texture.
  79750. */
  79751. HDRCubeTexture.prototype.loadTexture = function () {
  79752. if (this._isBABYLONPreprocessed) {
  79753. this.loadBabylonTexture();
  79754. }
  79755. else {
  79756. this.loadHDRTexture();
  79757. }
  79758. };
  79759. HDRCubeTexture.prototype.clone = function () {
  79760. var scene = this.getScene();
  79761. if (!scene) {
  79762. return this;
  79763. }
  79764. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79765. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79766. // Base texture
  79767. newTexture.level = this.level;
  79768. newTexture.wrapU = this.wrapU;
  79769. newTexture.wrapV = this.wrapV;
  79770. newTexture.coordinatesIndex = this.coordinatesIndex;
  79771. newTexture.coordinatesMode = this.coordinatesMode;
  79772. return newTexture;
  79773. };
  79774. // Methods
  79775. HDRCubeTexture.prototype.delayLoad = function () {
  79776. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79777. return;
  79778. }
  79779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79780. this._texture = this._getFromCache(this.url, this._noMipmap);
  79781. if (!this._texture) {
  79782. this.loadTexture();
  79783. }
  79784. };
  79785. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79786. return this._textureMatrix;
  79787. };
  79788. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79789. this._textureMatrix = value;
  79790. };
  79791. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79792. var texture = null;
  79793. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79794. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79795. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79796. texture.name = parsedTexture.name;
  79797. texture.hasAlpha = parsedTexture.hasAlpha;
  79798. texture.level = parsedTexture.level;
  79799. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79800. texture.isBlocking = parsedTexture.isBlocking;
  79801. }
  79802. if (texture) {
  79803. if (parsedTexture.boundingBoxPosition) {
  79804. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79805. }
  79806. if (parsedTexture.boundingBoxSize) {
  79807. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79808. }
  79809. if (parsedTexture.rotationY) {
  79810. texture.rotationY = parsedTexture.rotationY;
  79811. }
  79812. }
  79813. return texture;
  79814. };
  79815. HDRCubeTexture.prototype.serialize = function () {
  79816. if (!this.name) {
  79817. return null;
  79818. }
  79819. var serializationObject = {};
  79820. serializationObject.name = this.name;
  79821. serializationObject.hasAlpha = this.hasAlpha;
  79822. serializationObject.isCube = true;
  79823. serializationObject.level = this.level;
  79824. serializationObject.size = this._size;
  79825. serializationObject.coordinatesMode = this.coordinatesMode;
  79826. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79827. serializationObject.generateHarmonics = this._generateHarmonics;
  79828. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79829. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79830. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79831. serializationObject.noMipmap = this._noMipmap;
  79832. serializationObject.isBlocking = this._isBlocking;
  79833. serializationObject.rotationY = this._rotationY;
  79834. return serializationObject;
  79835. };
  79836. /**
  79837. * Saves as a file the data contained in the texture in a binary format.
  79838. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79839. * as the spherical used in the lighting.
  79840. * @param url The HDR file url.
  79841. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79842. * @param onError Method called if any error happens during download.
  79843. * @return The packed binary data.
  79844. */
  79845. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79846. if (onError === void 0) { onError = null; }
  79847. var callback = function (buffer) {
  79848. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79849. // Returns a URL you can use as a href.
  79850. var objUrl = window.URL.createObjectURL(data);
  79851. // Simulates a link to it and click to dowload.
  79852. var a = document.createElement("a");
  79853. document.body.appendChild(a);
  79854. a.style.display = "none";
  79855. a.href = objUrl;
  79856. a.download = "envmap.babylon.hdr";
  79857. a.click();
  79858. };
  79859. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79860. };
  79861. /**
  79862. * Serializes the data contained in the texture in a binary format.
  79863. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79864. * as the spherical used in the lighting.
  79865. * @param url The HDR file url.
  79866. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79867. * @param onError Method called if any error happens during download.
  79868. * @return The packed binary data.
  79869. */
  79870. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79871. if (onError === void 0) { onError = null; }
  79872. // Needs the url tho create the texture.
  79873. if (!url) {
  79874. return;
  79875. }
  79876. // Check Power of two size.
  79877. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  79878. return;
  79879. }
  79880. // Coming Back in 3.x.
  79881. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79882. };
  79883. HDRCubeTexture._facesMapping = [
  79884. "right",
  79885. "left",
  79886. "up",
  79887. "down",
  79888. "front",
  79889. "back"
  79890. ];
  79891. return HDRCubeTexture;
  79892. }(BABYLON.BaseTexture));
  79893. BABYLON.HDRCubeTexture = HDRCubeTexture;
  79894. })(BABYLON || (BABYLON = {}));
  79895. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  79896. var BABYLON;
  79897. (function (BABYLON) {
  79898. var IndexedVector2 = /** @class */ (function (_super) {
  79899. __extends(IndexedVector2, _super);
  79900. function IndexedVector2(original, index) {
  79901. var _this = _super.call(this, original.x, original.y) || this;
  79902. _this.index = index;
  79903. return _this;
  79904. }
  79905. return IndexedVector2;
  79906. }(BABYLON.Vector2));
  79907. var PolygonPoints = /** @class */ (function () {
  79908. function PolygonPoints() {
  79909. this.elements = new Array();
  79910. }
  79911. PolygonPoints.prototype.add = function (originalPoints) {
  79912. var _this = this;
  79913. var result = new Array();
  79914. originalPoints.forEach(function (point) {
  79915. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79916. var newPoint = new IndexedVector2(point, _this.elements.length);
  79917. result.push(newPoint);
  79918. _this.elements.push(newPoint);
  79919. }
  79920. });
  79921. return result;
  79922. };
  79923. PolygonPoints.prototype.computeBounds = function () {
  79924. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79925. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79926. this.elements.forEach(function (point) {
  79927. // x
  79928. if (point.x < lmin.x) {
  79929. lmin.x = point.x;
  79930. }
  79931. else if (point.x > lmax.x) {
  79932. lmax.x = point.x;
  79933. }
  79934. // y
  79935. if (point.y < lmin.y) {
  79936. lmin.y = point.y;
  79937. }
  79938. else if (point.y > lmax.y) {
  79939. lmax.y = point.y;
  79940. }
  79941. });
  79942. return {
  79943. min: lmin,
  79944. max: lmax,
  79945. width: lmax.x - lmin.x,
  79946. height: lmax.y - lmin.y
  79947. };
  79948. };
  79949. return PolygonPoints;
  79950. }());
  79951. var Polygon = /** @class */ (function () {
  79952. function Polygon() {
  79953. }
  79954. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79955. return [
  79956. new BABYLON.Vector2(xmin, ymin),
  79957. new BABYLON.Vector2(xmax, ymin),
  79958. new BABYLON.Vector2(xmax, ymax),
  79959. new BABYLON.Vector2(xmin, ymax)
  79960. ];
  79961. };
  79962. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79963. if (cx === void 0) { cx = 0; }
  79964. if (cy === void 0) { cy = 0; }
  79965. if (numberOfSides === void 0) { numberOfSides = 32; }
  79966. var result = new Array();
  79967. var angle = 0;
  79968. var increment = (Math.PI * 2) / numberOfSides;
  79969. for (var i = 0; i < numberOfSides; i++) {
  79970. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79971. angle -= increment;
  79972. }
  79973. return result;
  79974. };
  79975. Polygon.Parse = function (input) {
  79976. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79977. var i, result = [];
  79978. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79979. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79980. }
  79981. return result;
  79982. };
  79983. Polygon.StartingAt = function (x, y) {
  79984. return BABYLON.Path2.StartingAt(x, y);
  79985. };
  79986. return Polygon;
  79987. }());
  79988. BABYLON.Polygon = Polygon;
  79989. var PolygonMeshBuilder = /** @class */ (function () {
  79990. function PolygonMeshBuilder(name, contours, scene) {
  79991. this._points = new PolygonPoints();
  79992. this._outlinepoints = new PolygonPoints();
  79993. this._holes = new Array();
  79994. this._epoints = new Array();
  79995. this._eholes = new Array();
  79996. this._name = name;
  79997. this._scene = scene;
  79998. var points;
  79999. if (contours instanceof BABYLON.Path2) {
  80000. points = contours.getPoints();
  80001. }
  80002. else {
  80003. points = contours;
  80004. }
  80005. this._addToepoint(points);
  80006. this._points.add(points);
  80007. this._outlinepoints.add(points);
  80008. if (typeof earcut === 'undefined') {
  80009. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80010. }
  80011. }
  80012. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80013. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80014. var p = points_1[_i];
  80015. this._epoints.push(p.x, p.y);
  80016. }
  80017. };
  80018. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80019. this._points.add(hole);
  80020. var holepoints = new PolygonPoints();
  80021. holepoints.add(hole);
  80022. this._holes.push(holepoints);
  80023. this._eholes.push(this._epoints.length / 2);
  80024. this._addToepoint(hole);
  80025. return this;
  80026. };
  80027. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80028. var _this = this;
  80029. if (updatable === void 0) { updatable = false; }
  80030. if (depth === void 0) { depth = 0; }
  80031. var result = new BABYLON.Mesh(this._name, this._scene);
  80032. var normals = new Array();
  80033. var positions = new Array();
  80034. var uvs = new Array();
  80035. var bounds = this._points.computeBounds();
  80036. this._points.elements.forEach(function (p) {
  80037. normals.push(0, 1.0, 0);
  80038. positions.push(p.x, 0, p.y);
  80039. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80040. });
  80041. var indices = new Array();
  80042. var res = earcut(this._epoints, this._eholes, 2);
  80043. for (var i = 0; i < res.length; i++) {
  80044. indices.push(res[i]);
  80045. }
  80046. if (depth > 0) {
  80047. var positionscount = (positions.length / 3); //get the current pointcount
  80048. this._points.elements.forEach(function (p) {
  80049. normals.push(0, -1.0, 0);
  80050. positions.push(p.x, -depth, p.y);
  80051. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80052. });
  80053. var totalCount = indices.length;
  80054. for (var i = 0; i < totalCount; i += 3) {
  80055. var i0 = indices[i + 0];
  80056. var i1 = indices[i + 1];
  80057. var i2 = indices[i + 2];
  80058. indices.push(i2 + positionscount);
  80059. indices.push(i1 + positionscount);
  80060. indices.push(i0 + positionscount);
  80061. }
  80062. //Add the sides
  80063. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80064. this._holes.forEach(function (hole) {
  80065. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80066. });
  80067. }
  80068. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80069. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80070. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80071. result.setIndices(indices);
  80072. return result;
  80073. };
  80074. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80075. var StartIndex = positions.length / 3;
  80076. var ulength = 0;
  80077. for (var i = 0; i < points.elements.length; i++) {
  80078. var p = points.elements[i];
  80079. var p1;
  80080. if ((i + 1) > points.elements.length - 1) {
  80081. p1 = points.elements[0];
  80082. }
  80083. else {
  80084. p1 = points.elements[i + 1];
  80085. }
  80086. positions.push(p.x, 0, p.y);
  80087. positions.push(p.x, -depth, p.y);
  80088. positions.push(p1.x, 0, p1.y);
  80089. positions.push(p1.x, -depth, p1.y);
  80090. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80091. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80092. var v3 = v2.subtract(v1);
  80093. var v4 = new BABYLON.Vector3(0, 1, 0);
  80094. var vn = BABYLON.Vector3.Cross(v3, v4);
  80095. vn = vn.normalize();
  80096. uvs.push(ulength / bounds.width, 0);
  80097. uvs.push(ulength / bounds.width, 1);
  80098. ulength += v3.length();
  80099. uvs.push((ulength / bounds.width), 0);
  80100. uvs.push((ulength / bounds.width), 1);
  80101. if (!flip) {
  80102. normals.push(-vn.x, -vn.y, -vn.z);
  80103. normals.push(-vn.x, -vn.y, -vn.z);
  80104. normals.push(-vn.x, -vn.y, -vn.z);
  80105. normals.push(-vn.x, -vn.y, -vn.z);
  80106. indices.push(StartIndex);
  80107. indices.push(StartIndex + 1);
  80108. indices.push(StartIndex + 2);
  80109. indices.push(StartIndex + 1);
  80110. indices.push(StartIndex + 3);
  80111. indices.push(StartIndex + 2);
  80112. }
  80113. else {
  80114. normals.push(vn.x, vn.y, vn.z);
  80115. normals.push(vn.x, vn.y, vn.z);
  80116. normals.push(vn.x, vn.y, vn.z);
  80117. normals.push(vn.x, vn.y, vn.z);
  80118. indices.push(StartIndex);
  80119. indices.push(StartIndex + 2);
  80120. indices.push(StartIndex + 1);
  80121. indices.push(StartIndex + 1);
  80122. indices.push(StartIndex + 2);
  80123. indices.push(StartIndex + 3);
  80124. }
  80125. StartIndex += 4;
  80126. }
  80127. ;
  80128. };
  80129. return PolygonMeshBuilder;
  80130. }());
  80131. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80132. })(BABYLON || (BABYLON = {}));
  80133. //# sourceMappingURL=babylon.polygonMesh.js.map
  80134. var BABYLON;
  80135. (function (BABYLON) {
  80136. // Unique ID when we import meshes from Babylon to CSG
  80137. var currentCSGMeshId = 0;
  80138. // # class Vertex
  80139. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80140. // one to provide additional features like texture coordinates and vertex
  80141. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80142. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80143. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80144. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80145. // is not used anywhere else.
  80146. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80147. var Vertex = /** @class */ (function () {
  80148. function Vertex(pos, normal, uv) {
  80149. this.pos = pos;
  80150. this.normal = normal;
  80151. this.uv = uv;
  80152. }
  80153. Vertex.prototype.clone = function () {
  80154. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80155. };
  80156. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80157. // orientation of a polygon is flipped.
  80158. Vertex.prototype.flip = function () {
  80159. this.normal = this.normal.scale(-1);
  80160. };
  80161. // Create a new vertex between this vertex and `other` by linearly
  80162. // interpolating all properties using a parameter of `t`. Subclasses should
  80163. // override this to interpolate additional properties.
  80164. Vertex.prototype.interpolate = function (other, t) {
  80165. 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));
  80166. };
  80167. return Vertex;
  80168. }());
  80169. // # class Plane
  80170. // Represents a plane in 3D space.
  80171. var Plane = /** @class */ (function () {
  80172. function Plane(normal, w) {
  80173. this.normal = normal;
  80174. this.w = w;
  80175. }
  80176. Plane.FromPoints = function (a, b, c) {
  80177. var v0 = c.subtract(a);
  80178. var v1 = b.subtract(a);
  80179. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80180. return null;
  80181. }
  80182. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80183. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80184. };
  80185. Plane.prototype.clone = function () {
  80186. return new Plane(this.normal.clone(), this.w);
  80187. };
  80188. Plane.prototype.flip = function () {
  80189. this.normal.scaleInPlace(-1);
  80190. this.w = -this.w;
  80191. };
  80192. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80193. // fragments in the appropriate lists. Coplanar polygons go into either
  80194. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80195. // respect to this plane. Polygons in front or in back of this plane go into
  80196. // either `front` or `back`.
  80197. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80198. var COPLANAR = 0;
  80199. var FRONT = 1;
  80200. var BACK = 2;
  80201. var SPANNING = 3;
  80202. // Classify each point as well as the entire polygon into one of the above
  80203. // four classes.
  80204. var polygonType = 0;
  80205. var types = [];
  80206. var i;
  80207. var t;
  80208. for (i = 0; i < polygon.vertices.length; i++) {
  80209. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80210. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80211. polygonType |= type;
  80212. types.push(type);
  80213. }
  80214. // Put the polygon in the correct list, splitting it when necessary.
  80215. switch (polygonType) {
  80216. case COPLANAR:
  80217. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80218. break;
  80219. case FRONT:
  80220. front.push(polygon);
  80221. break;
  80222. case BACK:
  80223. back.push(polygon);
  80224. break;
  80225. case SPANNING:
  80226. var f = [], b = [];
  80227. for (i = 0; i < polygon.vertices.length; i++) {
  80228. var j = (i + 1) % polygon.vertices.length;
  80229. var ti = types[i], tj = types[j];
  80230. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80231. if (ti !== BACK)
  80232. f.push(vi);
  80233. if (ti !== FRONT)
  80234. b.push(ti !== BACK ? vi.clone() : vi);
  80235. if ((ti | tj) === SPANNING) {
  80236. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80237. var v = vi.interpolate(vj, t);
  80238. f.push(v);
  80239. b.push(v.clone());
  80240. }
  80241. }
  80242. var poly;
  80243. if (f.length >= 3) {
  80244. poly = new Polygon(f, polygon.shared);
  80245. if (poly.plane)
  80246. front.push(poly);
  80247. }
  80248. if (b.length >= 3) {
  80249. poly = new Polygon(b, polygon.shared);
  80250. if (poly.plane)
  80251. back.push(poly);
  80252. }
  80253. break;
  80254. }
  80255. };
  80256. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80257. // point is on the plane.
  80258. Plane.EPSILON = 1e-5;
  80259. return Plane;
  80260. }());
  80261. // # class Polygon
  80262. // Represents a convex polygon. The vertices used to initialize a polygon must
  80263. // be coplanar and form a convex loop.
  80264. //
  80265. // Each convex polygon has a `shared` property, which is shared between all
  80266. // polygons that are clones of each other or were split from the same polygon.
  80267. // This can be used to define per-polygon properties (such as surface color).
  80268. var Polygon = /** @class */ (function () {
  80269. function Polygon(vertices, shared) {
  80270. this.vertices = vertices;
  80271. this.shared = shared;
  80272. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80273. }
  80274. Polygon.prototype.clone = function () {
  80275. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80276. return new Polygon(vertices, this.shared);
  80277. };
  80278. Polygon.prototype.flip = function () {
  80279. this.vertices.reverse().map(function (v) { v.flip(); });
  80280. this.plane.flip();
  80281. };
  80282. return Polygon;
  80283. }());
  80284. // # class Node
  80285. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80286. // by picking a polygon to split along. That polygon (and all other coplanar
  80287. // polygons) are added directly to that node and the other polygons are added to
  80288. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80289. // no distinction between internal and leaf nodes.
  80290. var Node = /** @class */ (function () {
  80291. function Node(polygons) {
  80292. this.plane = null;
  80293. this.front = null;
  80294. this.back = null;
  80295. this.polygons = new Array();
  80296. if (polygons) {
  80297. this.build(polygons);
  80298. }
  80299. }
  80300. Node.prototype.clone = function () {
  80301. var node = new Node();
  80302. node.plane = this.plane && this.plane.clone();
  80303. node.front = this.front && this.front.clone();
  80304. node.back = this.back && this.back.clone();
  80305. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80306. return node;
  80307. };
  80308. // Convert solid space to empty space and empty space to solid space.
  80309. Node.prototype.invert = function () {
  80310. for (var i = 0; i < this.polygons.length; i++) {
  80311. this.polygons[i].flip();
  80312. }
  80313. if (this.plane) {
  80314. this.plane.flip();
  80315. }
  80316. if (this.front) {
  80317. this.front.invert();
  80318. }
  80319. if (this.back) {
  80320. this.back.invert();
  80321. }
  80322. var temp = this.front;
  80323. this.front = this.back;
  80324. this.back = temp;
  80325. };
  80326. // Recursively remove all polygons in `polygons` that are inside this BSP
  80327. // tree.
  80328. Node.prototype.clipPolygons = function (polygons) {
  80329. if (!this.plane)
  80330. return polygons.slice();
  80331. var front = new Array(), back = new Array();
  80332. for (var i = 0; i < polygons.length; i++) {
  80333. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80334. }
  80335. if (this.front) {
  80336. front = this.front.clipPolygons(front);
  80337. }
  80338. if (this.back) {
  80339. back = this.back.clipPolygons(back);
  80340. }
  80341. else {
  80342. back = [];
  80343. }
  80344. return front.concat(back);
  80345. };
  80346. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80347. // `bsp`.
  80348. Node.prototype.clipTo = function (bsp) {
  80349. this.polygons = bsp.clipPolygons(this.polygons);
  80350. if (this.front)
  80351. this.front.clipTo(bsp);
  80352. if (this.back)
  80353. this.back.clipTo(bsp);
  80354. };
  80355. // Return a list of all polygons in this BSP tree.
  80356. Node.prototype.allPolygons = function () {
  80357. var polygons = this.polygons.slice();
  80358. if (this.front)
  80359. polygons = polygons.concat(this.front.allPolygons());
  80360. if (this.back)
  80361. polygons = polygons.concat(this.back.allPolygons());
  80362. return polygons;
  80363. };
  80364. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80365. // new polygons are filtered down to the bottom of the tree and become new
  80366. // nodes there. Each set of polygons is partitioned using the first polygon
  80367. // (no heuristic is used to pick a good split).
  80368. Node.prototype.build = function (polygons) {
  80369. if (!polygons.length)
  80370. return;
  80371. if (!this.plane)
  80372. this.plane = polygons[0].plane.clone();
  80373. var front = new Array(), back = new Array();
  80374. for (var i = 0; i < polygons.length; i++) {
  80375. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80376. }
  80377. if (front.length) {
  80378. if (!this.front)
  80379. this.front = new Node();
  80380. this.front.build(front);
  80381. }
  80382. if (back.length) {
  80383. if (!this.back)
  80384. this.back = new Node();
  80385. this.back.build(back);
  80386. }
  80387. };
  80388. return Node;
  80389. }());
  80390. var CSG = /** @class */ (function () {
  80391. function CSG() {
  80392. this.polygons = new Array();
  80393. }
  80394. // Convert BABYLON.Mesh to BABYLON.CSG
  80395. CSG.FromMesh = function (mesh) {
  80396. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80397. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80398. if (mesh instanceof BABYLON.Mesh) {
  80399. mesh.computeWorldMatrix(true);
  80400. matrix = mesh.getWorldMatrix();
  80401. meshPosition = mesh.position.clone();
  80402. meshRotation = mesh.rotation.clone();
  80403. if (mesh.rotationQuaternion) {
  80404. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80405. }
  80406. meshScaling = mesh.scaling.clone();
  80407. }
  80408. else {
  80409. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80410. }
  80411. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80412. var subMeshes = mesh.subMeshes;
  80413. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80414. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80415. vertices = [];
  80416. for (var j = 0; j < 3; j++) {
  80417. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80418. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80419. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80420. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80421. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80422. vertex = new Vertex(position, normal, uv);
  80423. vertices.push(vertex);
  80424. }
  80425. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80426. // To handle the case of degenerated triangle
  80427. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80428. if (polygon.plane)
  80429. polygons.push(polygon);
  80430. }
  80431. }
  80432. var csg = CSG.FromPolygons(polygons);
  80433. csg.matrix = matrix;
  80434. csg.position = meshPosition;
  80435. csg.rotation = meshRotation;
  80436. csg.scaling = meshScaling;
  80437. csg.rotationQuaternion = meshRotationQuaternion;
  80438. currentCSGMeshId++;
  80439. return csg;
  80440. };
  80441. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80442. CSG.FromPolygons = function (polygons) {
  80443. var csg = new CSG();
  80444. csg.polygons = polygons;
  80445. return csg;
  80446. };
  80447. CSG.prototype.clone = function () {
  80448. var csg = new CSG();
  80449. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80450. csg.copyTransformAttributes(this);
  80451. return csg;
  80452. };
  80453. CSG.prototype.union = function (csg) {
  80454. var a = new Node(this.clone().polygons);
  80455. var b = new Node(csg.clone().polygons);
  80456. a.clipTo(b);
  80457. b.clipTo(a);
  80458. b.invert();
  80459. b.clipTo(a);
  80460. b.invert();
  80461. a.build(b.allPolygons());
  80462. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80463. };
  80464. CSG.prototype.unionInPlace = function (csg) {
  80465. var a = new Node(this.polygons);
  80466. var b = new Node(csg.polygons);
  80467. a.clipTo(b);
  80468. b.clipTo(a);
  80469. b.invert();
  80470. b.clipTo(a);
  80471. b.invert();
  80472. a.build(b.allPolygons());
  80473. this.polygons = a.allPolygons();
  80474. };
  80475. CSG.prototype.subtract = function (csg) {
  80476. var a = new Node(this.clone().polygons);
  80477. var b = new Node(csg.clone().polygons);
  80478. a.invert();
  80479. a.clipTo(b);
  80480. b.clipTo(a);
  80481. b.invert();
  80482. b.clipTo(a);
  80483. b.invert();
  80484. a.build(b.allPolygons());
  80485. a.invert();
  80486. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80487. };
  80488. CSG.prototype.subtractInPlace = function (csg) {
  80489. var a = new Node(this.polygons);
  80490. var b = new Node(csg.polygons);
  80491. a.invert();
  80492. a.clipTo(b);
  80493. b.clipTo(a);
  80494. b.invert();
  80495. b.clipTo(a);
  80496. b.invert();
  80497. a.build(b.allPolygons());
  80498. a.invert();
  80499. this.polygons = a.allPolygons();
  80500. };
  80501. CSG.prototype.intersect = function (csg) {
  80502. var a = new Node(this.clone().polygons);
  80503. var b = new Node(csg.clone().polygons);
  80504. a.invert();
  80505. b.clipTo(a);
  80506. b.invert();
  80507. a.clipTo(b);
  80508. b.clipTo(a);
  80509. a.build(b.allPolygons());
  80510. a.invert();
  80511. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80512. };
  80513. CSG.prototype.intersectInPlace = function (csg) {
  80514. var a = new Node(this.polygons);
  80515. var b = new Node(csg.polygons);
  80516. a.invert();
  80517. b.clipTo(a);
  80518. b.invert();
  80519. a.clipTo(b);
  80520. b.clipTo(a);
  80521. a.build(b.allPolygons());
  80522. a.invert();
  80523. this.polygons = a.allPolygons();
  80524. };
  80525. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80526. // not modified.
  80527. CSG.prototype.inverse = function () {
  80528. var csg = this.clone();
  80529. csg.inverseInPlace();
  80530. return csg;
  80531. };
  80532. CSG.prototype.inverseInPlace = function () {
  80533. this.polygons.map(function (p) { p.flip(); });
  80534. };
  80535. // This is used to keep meshes transformations so they can be restored
  80536. // when we build back a Babylon Mesh
  80537. // NB : All CSG operations are performed in world coordinates
  80538. CSG.prototype.copyTransformAttributes = function (csg) {
  80539. this.matrix = csg.matrix;
  80540. this.position = csg.position;
  80541. this.rotation = csg.rotation;
  80542. this.scaling = csg.scaling;
  80543. this.rotationQuaternion = csg.rotationQuaternion;
  80544. return this;
  80545. };
  80546. // Build Raw mesh from CSG
  80547. // Coordinates here are in world space
  80548. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80549. var matrix = this.matrix.clone();
  80550. matrix.invert();
  80551. 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;
  80552. if (keepSubMeshes) {
  80553. // Sort Polygons, since subMeshes are indices range
  80554. polygons.sort(function (a, b) {
  80555. if (a.shared.meshId === b.shared.meshId) {
  80556. return a.shared.subMeshId - b.shared.subMeshId;
  80557. }
  80558. else {
  80559. return a.shared.meshId - b.shared.meshId;
  80560. }
  80561. });
  80562. }
  80563. for (var i = 0, il = polygons.length; i < il; i++) {
  80564. polygon = polygons[i];
  80565. // Building SubMeshes
  80566. if (!subMesh_dict[polygon.shared.meshId]) {
  80567. subMesh_dict[polygon.shared.meshId] = {};
  80568. }
  80569. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  80570. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  80571. indexStart: +Infinity,
  80572. indexEnd: -Infinity,
  80573. materialIndex: polygon.shared.materialIndex
  80574. };
  80575. }
  80576. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  80577. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  80578. polygonIndices[0] = 0;
  80579. polygonIndices[1] = j - 1;
  80580. polygonIndices[2] = j;
  80581. for (var k = 0; k < 3; k++) {
  80582. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  80583. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  80584. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  80585. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  80586. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  80587. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  80588. // Check if 2 points can be merged
  80589. if (!(typeof vertex_idx !== 'undefined' &&
  80590. normals[vertex_idx * 3] === localNormal.x &&
  80591. normals[vertex_idx * 3 + 1] === localNormal.y &&
  80592. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80593. uvs[vertex_idx * 2] === uv.x &&
  80594. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80595. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80596. uvs.push(uv.x, uv.y);
  80597. normals.push(normal.x, normal.y, normal.z);
  80598. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80599. }
  80600. indices.push(vertex_idx);
  80601. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80602. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80603. currentIndex++;
  80604. }
  80605. }
  80606. }
  80607. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80608. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80609. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80610. mesh.setIndices(indices, null);
  80611. if (keepSubMeshes) {
  80612. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80613. var materialIndexOffset = 0, materialMaxIndex;
  80614. mesh.subMeshes = new Array();
  80615. for (var m in subMesh_dict) {
  80616. materialMaxIndex = -1;
  80617. for (var sm in subMesh_dict[m]) {
  80618. subMesh_obj = subMesh_dict[m][sm];
  80619. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80620. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80621. }
  80622. materialIndexOffset += ++materialMaxIndex;
  80623. }
  80624. }
  80625. return mesh;
  80626. };
  80627. // Build Mesh from CSG taking material and transforms into account
  80628. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80629. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80630. mesh.material = material;
  80631. mesh.position.copyFrom(this.position);
  80632. mesh.rotation.copyFrom(this.rotation);
  80633. if (this.rotationQuaternion) {
  80634. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80635. }
  80636. mesh.scaling.copyFrom(this.scaling);
  80637. mesh.computeWorldMatrix(true);
  80638. return mesh;
  80639. };
  80640. return CSG;
  80641. }());
  80642. BABYLON.CSG = CSG;
  80643. })(BABYLON || (BABYLON = {}));
  80644. //# sourceMappingURL=babylon.csg.js.map
  80645. var BABYLON;
  80646. (function (BABYLON) {
  80647. var LensFlare = /** @class */ (function () {
  80648. function LensFlare(size, position, color, imgUrl, system) {
  80649. this.size = size;
  80650. this.position = position;
  80651. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80652. this.color = color || new BABYLON.Color3(1, 1, 1);
  80653. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80654. this._system = system;
  80655. system.lensFlares.push(this);
  80656. }
  80657. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80658. return new LensFlare(size, position, color, imgUrl, system);
  80659. };
  80660. LensFlare.prototype.dispose = function () {
  80661. if (this.texture) {
  80662. this.texture.dispose();
  80663. }
  80664. // Remove from scene
  80665. var index = this._system.lensFlares.indexOf(this);
  80666. this._system.lensFlares.splice(index, 1);
  80667. };
  80668. ;
  80669. return LensFlare;
  80670. }());
  80671. BABYLON.LensFlare = LensFlare;
  80672. })(BABYLON || (BABYLON = {}));
  80673. //# sourceMappingURL=babylon.lensFlare.js.map
  80674. var BABYLON;
  80675. (function (BABYLON) {
  80676. var LensFlareSystem = /** @class */ (function () {
  80677. function LensFlareSystem(name, emitter, scene) {
  80678. this.name = name;
  80679. this.lensFlares = new Array();
  80680. this.borderLimit = 300;
  80681. this.viewportBorder = 0;
  80682. this.layerMask = 0x0FFFFFFF;
  80683. this._vertexBuffers = {};
  80684. this._isEnabled = true;
  80685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80686. this._emitter = emitter;
  80687. this.id = name;
  80688. scene.lensFlareSystems.push(this);
  80689. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80690. var engine = scene.getEngine();
  80691. // VBO
  80692. var vertices = [];
  80693. vertices.push(1, 1);
  80694. vertices.push(-1, 1);
  80695. vertices.push(-1, -1);
  80696. vertices.push(1, -1);
  80697. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80698. // Indices
  80699. var indices = [];
  80700. indices.push(0);
  80701. indices.push(1);
  80702. indices.push(2);
  80703. indices.push(0);
  80704. indices.push(2);
  80705. indices.push(3);
  80706. this._indexBuffer = engine.createIndexBuffer(indices);
  80707. // Effects
  80708. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80709. }
  80710. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80711. get: function () {
  80712. return this._isEnabled;
  80713. },
  80714. set: function (value) {
  80715. this._isEnabled = value;
  80716. },
  80717. enumerable: true,
  80718. configurable: true
  80719. });
  80720. LensFlareSystem.prototype.getScene = function () {
  80721. return this._scene;
  80722. };
  80723. LensFlareSystem.prototype.getEmitter = function () {
  80724. return this._emitter;
  80725. };
  80726. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80727. this._emitter = newEmitter;
  80728. };
  80729. LensFlareSystem.prototype.getEmitterPosition = function () {
  80730. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80731. };
  80732. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80733. var position = this.getEmitterPosition();
  80734. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80735. this._positionX = position.x;
  80736. this._positionY = position.y;
  80737. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80738. if (this.viewportBorder > 0) {
  80739. globalViewport.x -= this.viewportBorder;
  80740. globalViewport.y -= this.viewportBorder;
  80741. globalViewport.width += this.viewportBorder * 2;
  80742. globalViewport.height += this.viewportBorder * 2;
  80743. position.x += this.viewportBorder;
  80744. position.y += this.viewportBorder;
  80745. this._positionX += this.viewportBorder;
  80746. this._positionY += this.viewportBorder;
  80747. }
  80748. if (position.z > 0) {
  80749. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80750. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80751. return true;
  80752. }
  80753. return true;
  80754. }
  80755. return false;
  80756. };
  80757. LensFlareSystem.prototype._isVisible = function () {
  80758. if (!this._isEnabled || !this._scene.activeCamera) {
  80759. return false;
  80760. }
  80761. var emitterPosition = this.getEmitterPosition();
  80762. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80763. var distance = direction.length();
  80764. direction.normalize();
  80765. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80766. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80767. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80768. };
  80769. LensFlareSystem.prototype.render = function () {
  80770. if (!this._effect.isReady() || !this._scene.activeCamera)
  80771. return false;
  80772. var engine = this._scene.getEngine();
  80773. var viewport = this._scene.activeCamera.viewport;
  80774. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80775. // Position
  80776. if (!this.computeEffectivePosition(globalViewport)) {
  80777. return false;
  80778. }
  80779. // Visibility
  80780. if (!this._isVisible()) {
  80781. return false;
  80782. }
  80783. // Intensity
  80784. var awayX;
  80785. var awayY;
  80786. if (this._positionX < this.borderLimit + globalViewport.x) {
  80787. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80788. }
  80789. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80790. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80791. }
  80792. else {
  80793. awayX = 0;
  80794. }
  80795. if (this._positionY < this.borderLimit + globalViewport.y) {
  80796. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80797. }
  80798. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80799. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80800. }
  80801. else {
  80802. awayY = 0;
  80803. }
  80804. var away = (awayX > awayY) ? awayX : awayY;
  80805. away -= this.viewportBorder;
  80806. if (away > this.borderLimit) {
  80807. away = this.borderLimit;
  80808. }
  80809. var intensity = 1.0 - (away / this.borderLimit);
  80810. if (intensity < 0) {
  80811. return false;
  80812. }
  80813. if (intensity > 1.0) {
  80814. intensity = 1.0;
  80815. }
  80816. if (this.viewportBorder > 0) {
  80817. globalViewport.x += this.viewportBorder;
  80818. globalViewport.y += this.viewportBorder;
  80819. globalViewport.width -= this.viewportBorder * 2;
  80820. globalViewport.height -= this.viewportBorder * 2;
  80821. this._positionX -= this.viewportBorder;
  80822. this._positionY -= this.viewportBorder;
  80823. }
  80824. // Position
  80825. var centerX = globalViewport.x + globalViewport.width / 2;
  80826. var centerY = globalViewport.y + globalViewport.height / 2;
  80827. var distX = centerX - this._positionX;
  80828. var distY = centerY - this._positionY;
  80829. // Effects
  80830. engine.enableEffect(this._effect);
  80831. engine.setState(false);
  80832. engine.setDepthBuffer(false);
  80833. // VBOs
  80834. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80835. // Flares
  80836. for (var index = 0; index < this.lensFlares.length; index++) {
  80837. var flare = this.lensFlares[index];
  80838. engine.setAlphaMode(flare.alphaMode);
  80839. var x = centerX - (distX * flare.position);
  80840. var y = centerY - (distY * flare.position);
  80841. var cw = flare.size;
  80842. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80843. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80844. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80845. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80846. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80847. // Texture
  80848. this._effect.setTexture("textureSampler", flare.texture);
  80849. // Color
  80850. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80851. // Draw order
  80852. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80853. }
  80854. engine.setDepthBuffer(true);
  80855. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80856. return true;
  80857. };
  80858. LensFlareSystem.prototype.dispose = function () {
  80859. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80860. if (vertexBuffer) {
  80861. vertexBuffer.dispose();
  80862. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80863. }
  80864. if (this._indexBuffer) {
  80865. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80866. this._indexBuffer = null;
  80867. }
  80868. while (this.lensFlares.length) {
  80869. this.lensFlares[0].dispose();
  80870. }
  80871. // Remove from scene
  80872. var index = this._scene.lensFlareSystems.indexOf(this);
  80873. this._scene.lensFlareSystems.splice(index, 1);
  80874. };
  80875. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80876. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80877. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80878. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80879. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80880. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80881. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80882. var parsedFlare = parsedLensFlareSystem.flares[index];
  80883. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80884. }
  80885. return lensFlareSystem;
  80886. };
  80887. LensFlareSystem.prototype.serialize = function () {
  80888. var serializationObject = {};
  80889. serializationObject.id = this.id;
  80890. serializationObject.name = this.name;
  80891. serializationObject.emitterId = this.getEmitter().id;
  80892. serializationObject.borderLimit = this.borderLimit;
  80893. serializationObject.flares = [];
  80894. for (var index = 0; index < this.lensFlares.length; index++) {
  80895. var flare = this.lensFlares[index];
  80896. serializationObject.flares.push({
  80897. size: flare.size,
  80898. position: flare.position,
  80899. color: flare.color.asArray(),
  80900. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80901. });
  80902. }
  80903. return serializationObject;
  80904. };
  80905. return LensFlareSystem;
  80906. }());
  80907. BABYLON.LensFlareSystem = LensFlareSystem;
  80908. })(BABYLON || (BABYLON = {}));
  80909. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80910. var BABYLON;
  80911. (function (BABYLON) {
  80912. /**
  80913. * This is a holder class for the physics joint created by the physics plugin.
  80914. * It holds a set of functions to control the underlying joint.
  80915. */
  80916. var PhysicsJoint = /** @class */ (function () {
  80917. function PhysicsJoint(type, jointData) {
  80918. this.type = type;
  80919. this.jointData = jointData;
  80920. jointData.nativeParams = jointData.nativeParams || {};
  80921. }
  80922. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80923. get: function () {
  80924. return this._physicsJoint;
  80925. },
  80926. set: function (newJoint) {
  80927. if (this._physicsJoint) {
  80928. //remove from the wolrd
  80929. }
  80930. this._physicsJoint = newJoint;
  80931. },
  80932. enumerable: true,
  80933. configurable: true
  80934. });
  80935. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80936. set: function (physicsPlugin) {
  80937. this._physicsPlugin = physicsPlugin;
  80938. },
  80939. enumerable: true,
  80940. configurable: true
  80941. });
  80942. /**
  80943. * Execute a function that is physics-plugin specific.
  80944. * @param {Function} func the function that will be executed.
  80945. * It accepts two parameters: the physics world and the physics joint.
  80946. */
  80947. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80948. func(this._physicsPlugin.world, this._physicsJoint);
  80949. };
  80950. //TODO check if the native joints are the same
  80951. //Joint Types
  80952. PhysicsJoint.DistanceJoint = 0;
  80953. PhysicsJoint.HingeJoint = 1;
  80954. PhysicsJoint.BallAndSocketJoint = 2;
  80955. PhysicsJoint.WheelJoint = 3;
  80956. PhysicsJoint.SliderJoint = 4;
  80957. //OIMO
  80958. PhysicsJoint.PrismaticJoint = 5;
  80959. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80960. PhysicsJoint.UniversalJoint = 6;
  80961. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80962. //Cannon
  80963. //Similar to a Ball-Joint. Different in params
  80964. PhysicsJoint.PointToPointJoint = 8;
  80965. //Cannon only at the moment
  80966. PhysicsJoint.SpringJoint = 9;
  80967. PhysicsJoint.LockJoint = 10;
  80968. return PhysicsJoint;
  80969. }());
  80970. BABYLON.PhysicsJoint = PhysicsJoint;
  80971. /**
  80972. * A class representing a physics distance joint.
  80973. */
  80974. var DistanceJoint = /** @class */ (function (_super) {
  80975. __extends(DistanceJoint, _super);
  80976. function DistanceJoint(jointData) {
  80977. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80978. }
  80979. /**
  80980. * Update the predefined distance.
  80981. */
  80982. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80983. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80984. };
  80985. return DistanceJoint;
  80986. }(PhysicsJoint));
  80987. BABYLON.DistanceJoint = DistanceJoint;
  80988. var MotorEnabledJoint = /** @class */ (function (_super) {
  80989. __extends(MotorEnabledJoint, _super);
  80990. function MotorEnabledJoint(type, jointData) {
  80991. return _super.call(this, type, jointData) || this;
  80992. }
  80993. /**
  80994. * Set the motor values.
  80995. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80996. * @param {number} force the force to apply
  80997. * @param {number} maxForce max force for this motor.
  80998. */
  80999. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81000. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81001. };
  81002. /**
  81003. * Set the motor's limits.
  81004. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81005. */
  81006. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81007. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81008. };
  81009. return MotorEnabledJoint;
  81010. }(PhysicsJoint));
  81011. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81012. /**
  81013. * This class represents a single hinge physics joint
  81014. */
  81015. var HingeJoint = /** @class */ (function (_super) {
  81016. __extends(HingeJoint, _super);
  81017. function HingeJoint(jointData) {
  81018. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81019. }
  81020. /**
  81021. * Set the motor values.
  81022. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81023. * @param {number} force the force to apply
  81024. * @param {number} maxForce max force for this motor.
  81025. */
  81026. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81027. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81028. };
  81029. /**
  81030. * Set the motor's limits.
  81031. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81032. */
  81033. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81034. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81035. };
  81036. return HingeJoint;
  81037. }(MotorEnabledJoint));
  81038. BABYLON.HingeJoint = HingeJoint;
  81039. /**
  81040. * This class represents a dual hinge physics joint (same as wheel joint)
  81041. */
  81042. var Hinge2Joint = /** @class */ (function (_super) {
  81043. __extends(Hinge2Joint, _super);
  81044. function Hinge2Joint(jointData) {
  81045. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81046. }
  81047. /**
  81048. * Set the motor values.
  81049. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81050. * @param {number} force the force to apply
  81051. * @param {number} maxForce max force for this motor.
  81052. * @param {motorIndex} the motor's index, 0 or 1.
  81053. */
  81054. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81055. if (motorIndex === void 0) { motorIndex = 0; }
  81056. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81057. };
  81058. /**
  81059. * Set the motor limits.
  81060. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81061. * @param {number} upperLimit the upper limit
  81062. * @param {number} lowerLimit lower limit
  81063. * @param {motorIndex} the motor's index, 0 or 1.
  81064. */
  81065. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81066. if (motorIndex === void 0) { motorIndex = 0; }
  81067. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81068. };
  81069. return Hinge2Joint;
  81070. }(MotorEnabledJoint));
  81071. BABYLON.Hinge2Joint = Hinge2Joint;
  81072. })(BABYLON || (BABYLON = {}));
  81073. //# sourceMappingURL=babylon.physicsJoint.js.map
  81074. var BABYLON;
  81075. (function (BABYLON) {
  81076. var PhysicsImpostor = /** @class */ (function () {
  81077. function PhysicsImpostor(object, type, _options, _scene) {
  81078. if (_options === void 0) { _options = { mass: 0 }; }
  81079. var _this = this;
  81080. this.object = object;
  81081. this.type = type;
  81082. this._options = _options;
  81083. this._scene = _scene;
  81084. this._bodyUpdateRequired = false;
  81085. this._onBeforePhysicsStepCallbacks = new Array();
  81086. this._onAfterPhysicsStepCallbacks = new Array();
  81087. this._onPhysicsCollideCallbacks = [];
  81088. this._deltaPosition = BABYLON.Vector3.Zero();
  81089. this._isDisposed = false;
  81090. //temp variables for parent rotation calculations
  81091. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81092. this._tmpQuat = new BABYLON.Quaternion();
  81093. this._tmpQuat2 = new BABYLON.Quaternion();
  81094. /**
  81095. * this function is executed by the physics engine.
  81096. */
  81097. this.beforeStep = function () {
  81098. if (!_this._physicsEngine) {
  81099. return;
  81100. }
  81101. _this.object.translate(_this._deltaPosition, -1);
  81102. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81103. _this.object.computeWorldMatrix(false);
  81104. if (_this.object.parent && _this.object.rotationQuaternion) {
  81105. _this.getParentsRotation();
  81106. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81107. }
  81108. else {
  81109. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81110. }
  81111. if (!_this._options.disableBidirectionalTransformation) {
  81112. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81113. }
  81114. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81115. func(_this);
  81116. });
  81117. };
  81118. /**
  81119. * this function is executed by the physics engine.
  81120. */
  81121. this.afterStep = function () {
  81122. if (!_this._physicsEngine) {
  81123. return;
  81124. }
  81125. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81126. func(_this);
  81127. });
  81128. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81129. // object has now its world rotation. needs to be converted to local.
  81130. if (_this.object.parent && _this.object.rotationQuaternion) {
  81131. _this.getParentsRotation();
  81132. _this._tmpQuat.conjugateInPlace();
  81133. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81134. }
  81135. // take the position set and make it the absolute position of this object.
  81136. _this.object.setAbsolutePosition(_this.object.position);
  81137. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81138. _this.object.translate(_this._deltaPosition, 1);
  81139. };
  81140. /**
  81141. * Legacy collision detection event support
  81142. */
  81143. this.onCollideEvent = null;
  81144. //event and body object due to cannon's event-based architecture.
  81145. this.onCollide = function (e) {
  81146. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81147. return;
  81148. }
  81149. if (!_this._physicsEngine) {
  81150. return;
  81151. }
  81152. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81153. if (otherImpostor) {
  81154. // Legacy collision detection event support
  81155. if (_this.onCollideEvent) {
  81156. _this.onCollideEvent(_this, otherImpostor);
  81157. }
  81158. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81159. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81160. }).forEach(function (obj) {
  81161. obj.callback(_this, otherImpostor);
  81162. });
  81163. }
  81164. };
  81165. //sanity check!
  81166. if (!this.object) {
  81167. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81168. return;
  81169. }
  81170. //legacy support for old syntax.
  81171. if (!this._scene && object.getScene) {
  81172. this._scene = object.getScene();
  81173. }
  81174. if (!this._scene) {
  81175. return;
  81176. }
  81177. this._physicsEngine = this._scene.getPhysicsEngine();
  81178. if (!this._physicsEngine) {
  81179. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81180. }
  81181. else {
  81182. //set the object's quaternion, if not set
  81183. if (!this.object.rotationQuaternion) {
  81184. if (this.object.rotation) {
  81185. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81186. }
  81187. else {
  81188. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81189. }
  81190. }
  81191. //default options params
  81192. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81193. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81194. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81195. this._joints = [];
  81196. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81197. if (!this.object.parent || this._options.ignoreParent) {
  81198. this._init();
  81199. }
  81200. else if (this.object.parent.physicsImpostor) {
  81201. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81202. }
  81203. }
  81204. }
  81205. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81206. get: function () {
  81207. return this._isDisposed;
  81208. },
  81209. enumerable: true,
  81210. configurable: true
  81211. });
  81212. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81213. get: function () {
  81214. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81215. },
  81216. set: function (value) {
  81217. this.setMass(value);
  81218. },
  81219. enumerable: true,
  81220. configurable: true
  81221. });
  81222. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81223. get: function () {
  81224. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81225. },
  81226. set: function (value) {
  81227. if (!this._physicsEngine) {
  81228. return;
  81229. }
  81230. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81231. },
  81232. enumerable: true,
  81233. configurable: true
  81234. });
  81235. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81236. get: function () {
  81237. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81238. },
  81239. set: function (value) {
  81240. if (!this._physicsEngine) {
  81241. return;
  81242. }
  81243. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81244. },
  81245. enumerable: true,
  81246. configurable: true
  81247. });
  81248. /**
  81249. * This function will completly initialize this impostor.
  81250. * It will create a new body - but only if this mesh has no parent.
  81251. * If it has, this impostor will not be used other than to define the impostor
  81252. * of the child mesh.
  81253. */
  81254. PhysicsImpostor.prototype._init = function () {
  81255. if (!this._physicsEngine) {
  81256. return;
  81257. }
  81258. this._physicsEngine.removeImpostor(this);
  81259. this.physicsBody = null;
  81260. this._parent = this._parent || this._getPhysicsParent();
  81261. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81262. this._physicsEngine.addImpostor(this);
  81263. }
  81264. };
  81265. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81266. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81267. var parentMesh = this.object.parent;
  81268. return parentMesh.physicsImpostor;
  81269. }
  81270. return null;
  81271. };
  81272. /**
  81273. * Should a new body be generated.
  81274. */
  81275. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81276. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81277. };
  81278. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81279. this.forceUpdate();
  81280. };
  81281. /**
  81282. * Force a regeneration of this or the parent's impostor's body.
  81283. * Use under cautious - This will remove all joints already implemented.
  81284. */
  81285. PhysicsImpostor.prototype.forceUpdate = function () {
  81286. this._init();
  81287. if (this.parent && !this._options.ignoreParent) {
  81288. this.parent.forceUpdate();
  81289. }
  81290. };
  81291. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81292. /*public get mesh(): AbstractMesh {
  81293. return this._mesh;
  81294. }*/
  81295. /**
  81296. * Gets the body that holds this impostor. Either its own, or its parent.
  81297. */
  81298. get: function () {
  81299. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81300. },
  81301. /**
  81302. * Set the physics body. Used mainly by the physics engine/plugin
  81303. */
  81304. set: function (physicsBody) {
  81305. if (this._physicsBody && this._physicsEngine) {
  81306. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81307. }
  81308. this._physicsBody = physicsBody;
  81309. this.resetUpdateFlags();
  81310. },
  81311. enumerable: true,
  81312. configurable: true
  81313. });
  81314. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81315. get: function () {
  81316. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81317. },
  81318. set: function (value) {
  81319. this._parent = value;
  81320. },
  81321. enumerable: true,
  81322. configurable: true
  81323. });
  81324. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81325. this._bodyUpdateRequired = false;
  81326. };
  81327. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81328. if (this.object.getBoundingInfo) {
  81329. var q = this.object.rotationQuaternion;
  81330. //reset rotation
  81331. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81332. //calculate the world matrix with no rotation
  81333. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81334. var boundingInfo = this.object.getBoundingInfo();
  81335. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81336. //bring back the rotation
  81337. this.object.rotationQuaternion = q;
  81338. //calculate the world matrix with the new rotation
  81339. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81340. return size;
  81341. }
  81342. else {
  81343. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81344. }
  81345. };
  81346. PhysicsImpostor.prototype.getObjectCenter = function () {
  81347. if (this.object.getBoundingInfo) {
  81348. var boundingInfo = this.object.getBoundingInfo();
  81349. return boundingInfo.boundingBox.centerWorld;
  81350. }
  81351. else {
  81352. return this.object.position;
  81353. }
  81354. };
  81355. /**
  81356. * Get a specific parametes from the options parameter.
  81357. */
  81358. PhysicsImpostor.prototype.getParam = function (paramName) {
  81359. return this._options[paramName];
  81360. };
  81361. /**
  81362. * Sets a specific parameter in the options given to the physics plugin
  81363. */
  81364. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81365. this._options[paramName] = value;
  81366. this._bodyUpdateRequired = true;
  81367. };
  81368. /**
  81369. * Specifically change the body's mass option. Won't recreate the physics body object
  81370. */
  81371. PhysicsImpostor.prototype.setMass = function (mass) {
  81372. if (this.getParam("mass") !== mass) {
  81373. this.setParam("mass", mass);
  81374. }
  81375. if (this._physicsEngine) {
  81376. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81377. }
  81378. };
  81379. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81380. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81381. };
  81382. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81383. if (this._physicsEngine) {
  81384. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81385. }
  81386. };
  81387. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81388. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81389. };
  81390. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81391. if (this._physicsEngine) {
  81392. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81393. }
  81394. };
  81395. /**
  81396. * Execute a function with the physics plugin native code.
  81397. * Provide a function the will have two variables - the world object and the physics body object.
  81398. */
  81399. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81400. if (this._physicsEngine) {
  81401. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81402. }
  81403. };
  81404. /**
  81405. * Register a function that will be executed before the physics world is stepping forward.
  81406. */
  81407. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81408. this._onBeforePhysicsStepCallbacks.push(func);
  81409. };
  81410. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81411. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81412. if (index > -1) {
  81413. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81414. }
  81415. else {
  81416. BABYLON.Tools.Warn("Function to remove was not found");
  81417. }
  81418. };
  81419. /**
  81420. * Register a function that will be executed after the physics step
  81421. */
  81422. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81423. this._onAfterPhysicsStepCallbacks.push(func);
  81424. };
  81425. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81426. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81427. if (index > -1) {
  81428. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81429. }
  81430. else {
  81431. BABYLON.Tools.Warn("Function to remove was not found");
  81432. }
  81433. };
  81434. /**
  81435. * register a function that will be executed when this impostor collides against a different body.
  81436. */
  81437. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81438. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81439. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81440. };
  81441. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81442. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81443. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81444. if (index > -1) {
  81445. this._onPhysicsCollideCallbacks.splice(index, 1);
  81446. }
  81447. else {
  81448. BABYLON.Tools.Warn("Function to remove was not found");
  81449. }
  81450. };
  81451. PhysicsImpostor.prototype.getParentsRotation = function () {
  81452. var parent = this.object.parent;
  81453. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81454. while (parent) {
  81455. if (parent.rotationQuaternion) {
  81456. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81457. }
  81458. else {
  81459. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81460. }
  81461. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81462. parent = parent.parent;
  81463. }
  81464. return this._tmpQuat;
  81465. };
  81466. /**
  81467. * Apply a force
  81468. */
  81469. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81470. if (this._physicsEngine) {
  81471. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81472. }
  81473. return this;
  81474. };
  81475. /**
  81476. * Apply an impulse
  81477. */
  81478. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81479. if (this._physicsEngine) {
  81480. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81481. }
  81482. return this;
  81483. };
  81484. /**
  81485. * A help function to create a joint.
  81486. */
  81487. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81488. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81489. this.addJoint(otherImpostor, joint);
  81490. return this;
  81491. };
  81492. /**
  81493. * Add a joint to this impostor with a different impostor.
  81494. */
  81495. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81496. this._joints.push({
  81497. otherImpostor: otherImpostor,
  81498. joint: joint
  81499. });
  81500. if (this._physicsEngine) {
  81501. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81502. }
  81503. return this;
  81504. };
  81505. /**
  81506. * Will keep this body still, in a sleep mode.
  81507. */
  81508. PhysicsImpostor.prototype.sleep = function () {
  81509. if (this._physicsEngine) {
  81510. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81511. }
  81512. return this;
  81513. };
  81514. /**
  81515. * Wake the body up.
  81516. */
  81517. PhysicsImpostor.prototype.wakeUp = function () {
  81518. if (this._physicsEngine) {
  81519. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81520. }
  81521. return this;
  81522. };
  81523. PhysicsImpostor.prototype.clone = function (newObject) {
  81524. if (!newObject)
  81525. return null;
  81526. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81527. };
  81528. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81529. var _this = this;
  81530. //no dispose if no physics engine is available.
  81531. if (!this._physicsEngine) {
  81532. return;
  81533. }
  81534. this._joints.forEach(function (j) {
  81535. if (_this._physicsEngine) {
  81536. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81537. }
  81538. });
  81539. //dispose the physics body
  81540. this._physicsEngine.removeImpostor(this);
  81541. if (this.parent) {
  81542. this.parent.forceUpdate();
  81543. }
  81544. else {
  81545. /*this._object.getChildMeshes().forEach(function(mesh) {
  81546. if (mesh.physicsImpostor) {
  81547. if (disposeChildren) {
  81548. mesh.physicsImpostor.dispose();
  81549. mesh.physicsImpostor = null;
  81550. }
  81551. }
  81552. })*/
  81553. }
  81554. this._isDisposed = true;
  81555. };
  81556. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81557. this._deltaPosition.copyFrom(position);
  81558. };
  81559. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  81560. if (!this._deltaRotation) {
  81561. this._deltaRotation = new BABYLON.Quaternion();
  81562. }
  81563. this._deltaRotation.copyFrom(rotation);
  81564. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  81565. };
  81566. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  81567. if (this._physicsEngine) {
  81568. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  81569. }
  81570. return this;
  81571. };
  81572. PhysicsImpostor.prototype.getRadius = function () {
  81573. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  81574. };
  81575. /**
  81576. * Sync a bone with this impostor
  81577. * @param bone The bone to sync to the impostor.
  81578. * @param boneMesh The mesh that the bone is influencing.
  81579. * @param jointPivot The pivot of the joint / bone in local space.
  81580. * @param distToJoint Optional distance from the impostor to the joint.
  81581. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81582. */
  81583. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  81584. var tempVec = PhysicsImpostor._tmpVecs[0];
  81585. var mesh = this.object;
  81586. if (mesh.rotationQuaternion) {
  81587. if (adjustRotation) {
  81588. var tempQuat = PhysicsImpostor._tmpQuat;
  81589. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81590. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81591. }
  81592. else {
  81593. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81594. }
  81595. }
  81596. tempVec.x = 0;
  81597. tempVec.y = 0;
  81598. tempVec.z = 0;
  81599. if (jointPivot) {
  81600. tempVec.x = jointPivot.x;
  81601. tempVec.y = jointPivot.y;
  81602. tempVec.z = jointPivot.z;
  81603. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81604. if (distToJoint === undefined || distToJoint === null) {
  81605. distToJoint = jointPivot.length();
  81606. }
  81607. tempVec.x *= distToJoint;
  81608. tempVec.y *= distToJoint;
  81609. tempVec.z *= distToJoint;
  81610. }
  81611. if (bone.getParent()) {
  81612. tempVec.addInPlace(mesh.getAbsolutePosition());
  81613. bone.setAbsolutePosition(tempVec, boneMesh);
  81614. }
  81615. else {
  81616. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81617. boneMesh.position.x -= tempVec.x;
  81618. boneMesh.position.y -= tempVec.y;
  81619. boneMesh.position.z -= tempVec.z;
  81620. }
  81621. };
  81622. /**
  81623. * Sync impostor to a bone
  81624. * @param bone The bone that the impostor will be synced to.
  81625. * @param boneMesh The mesh that the bone is influencing.
  81626. * @param jointPivot The pivot of the joint / bone in local space.
  81627. * @param distToJoint Optional distance from the impostor to the joint.
  81628. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81629. * @param boneAxis Optional vector3 axis the bone is aligned with
  81630. */
  81631. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81632. var mesh = this.object;
  81633. if (mesh.rotationQuaternion) {
  81634. if (adjustRotation) {
  81635. var tempQuat = PhysicsImpostor._tmpQuat;
  81636. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81637. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81638. }
  81639. else {
  81640. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81641. }
  81642. }
  81643. var pos = PhysicsImpostor._tmpVecs[0];
  81644. var boneDir = PhysicsImpostor._tmpVecs[1];
  81645. if (!boneAxis) {
  81646. boneAxis = PhysicsImpostor._tmpVecs[2];
  81647. boneAxis.x = 0;
  81648. boneAxis.y = 1;
  81649. boneAxis.z = 0;
  81650. }
  81651. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81652. bone.getAbsolutePositionToRef(boneMesh, pos);
  81653. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81654. distToJoint = jointPivot.length();
  81655. }
  81656. if (distToJoint !== undefined && distToJoint !== null) {
  81657. pos.x += boneDir.x * distToJoint;
  81658. pos.y += boneDir.y * distToJoint;
  81659. pos.z += boneDir.z * distToJoint;
  81660. }
  81661. mesh.setAbsolutePosition(pos);
  81662. };
  81663. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81664. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81665. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81666. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81667. //Impostor types
  81668. PhysicsImpostor.NoImpostor = 0;
  81669. PhysicsImpostor.SphereImpostor = 1;
  81670. PhysicsImpostor.BoxImpostor = 2;
  81671. PhysicsImpostor.PlaneImpostor = 3;
  81672. PhysicsImpostor.MeshImpostor = 4;
  81673. PhysicsImpostor.CylinderImpostor = 7;
  81674. PhysicsImpostor.ParticleImpostor = 8;
  81675. PhysicsImpostor.HeightmapImpostor = 9;
  81676. return PhysicsImpostor;
  81677. }());
  81678. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81679. })(BABYLON || (BABYLON = {}));
  81680. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81681. var BABYLON;
  81682. (function (BABYLON) {
  81683. var PhysicsEngine = /** @class */ (function () {
  81684. function PhysicsEngine(gravity, _physicsPlugin) {
  81685. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81686. this._physicsPlugin = _physicsPlugin;
  81687. //new methods and parameters
  81688. this._impostors = [];
  81689. this._joints = [];
  81690. if (!this._physicsPlugin.isSupported()) {
  81691. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81692. + "Please make sure it is included.");
  81693. }
  81694. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81695. this.setGravity(gravity);
  81696. this.setTimeStep();
  81697. }
  81698. PhysicsEngine.prototype.setGravity = function (gravity) {
  81699. this.gravity = gravity;
  81700. this._physicsPlugin.setGravity(this.gravity);
  81701. };
  81702. /**
  81703. * Set the time step of the physics engine.
  81704. * default is 1/60.
  81705. * To slow it down, enter 1/600 for example.
  81706. * To speed it up, 1/30
  81707. * @param {number} newTimeStep the new timestep to apply to this world.
  81708. */
  81709. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81710. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81711. this._physicsPlugin.setTimeStep(newTimeStep);
  81712. };
  81713. /**
  81714. * Get the time step of the physics engine.
  81715. */
  81716. PhysicsEngine.prototype.getTimeStep = function () {
  81717. return this._physicsPlugin.getTimeStep();
  81718. };
  81719. PhysicsEngine.prototype.dispose = function () {
  81720. this._impostors.forEach(function (impostor) {
  81721. impostor.dispose();
  81722. });
  81723. this._physicsPlugin.dispose();
  81724. };
  81725. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81726. return this._physicsPlugin.name;
  81727. };
  81728. /**
  81729. * Adding a new impostor for the impostor tracking.
  81730. * This will be done by the impostor itself.
  81731. * @param {PhysicsImpostor} impostor the impostor to add
  81732. */
  81733. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81734. impostor.uniqueId = this._impostors.push(impostor);
  81735. //if no parent, generate the body
  81736. if (!impostor.parent) {
  81737. this._physicsPlugin.generatePhysicsBody(impostor);
  81738. }
  81739. };
  81740. /**
  81741. * Remove an impostor from the engine.
  81742. * This impostor and its mesh will not longer be updated by the physics engine.
  81743. * @param {PhysicsImpostor} impostor the impostor to remove
  81744. */
  81745. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81746. var index = this._impostors.indexOf(impostor);
  81747. if (index > -1) {
  81748. var removed = this._impostors.splice(index, 1);
  81749. //Is it needed?
  81750. if (removed.length) {
  81751. //this will also remove it from the world.
  81752. removed[0].physicsBody = null;
  81753. }
  81754. }
  81755. };
  81756. /**
  81757. * Add a joint to the physics engine
  81758. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81759. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81760. * @param {PhysicsJoint} the joint that will connect both impostors.
  81761. */
  81762. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81763. var impostorJoint = {
  81764. mainImpostor: mainImpostor,
  81765. connectedImpostor: connectedImpostor,
  81766. joint: joint
  81767. };
  81768. joint.physicsPlugin = this._physicsPlugin;
  81769. this._joints.push(impostorJoint);
  81770. this._physicsPlugin.generateJoint(impostorJoint);
  81771. };
  81772. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81773. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81774. return (impostorJoint.connectedImpostor === connectedImpostor
  81775. && impostorJoint.joint === joint
  81776. && impostorJoint.mainImpostor === mainImpostor);
  81777. });
  81778. if (matchingJoints.length) {
  81779. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81780. //TODO remove it from the list as well
  81781. }
  81782. };
  81783. /**
  81784. * Called by the scene. no need to call it.
  81785. */
  81786. PhysicsEngine.prototype._step = function (delta) {
  81787. var _this = this;
  81788. //check if any mesh has no body / requires an update
  81789. this._impostors.forEach(function (impostor) {
  81790. if (impostor.isBodyInitRequired()) {
  81791. _this._physicsPlugin.generatePhysicsBody(impostor);
  81792. }
  81793. });
  81794. if (delta > 0.1) {
  81795. delta = 0.1;
  81796. }
  81797. else if (delta <= 0) {
  81798. delta = 1.0 / 60.0;
  81799. }
  81800. this._physicsPlugin.executeStep(delta, this._impostors);
  81801. };
  81802. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81803. return this._physicsPlugin;
  81804. };
  81805. PhysicsEngine.prototype.getImpostors = function () {
  81806. return this._impostors;
  81807. };
  81808. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81809. for (var i = 0; i < this._impostors.length; ++i) {
  81810. if (this._impostors[i].object === object) {
  81811. return this._impostors[i];
  81812. }
  81813. }
  81814. return null;
  81815. };
  81816. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81817. for (var i = 0; i < this._impostors.length; ++i) {
  81818. if (this._impostors[i].physicsBody === body) {
  81819. return this._impostors[i];
  81820. }
  81821. }
  81822. return null;
  81823. };
  81824. // Statics
  81825. PhysicsEngine.Epsilon = 0.001;
  81826. return PhysicsEngine;
  81827. }());
  81828. BABYLON.PhysicsEngine = PhysicsEngine;
  81829. })(BABYLON || (BABYLON = {}));
  81830. //# sourceMappingURL=babylon.physicsEngine.js.map
  81831. var BABYLON;
  81832. (function (BABYLON) {
  81833. var PhysicsHelper = /** @class */ (function () {
  81834. function PhysicsHelper(scene) {
  81835. this._scene = scene;
  81836. this._physicsEngine = this._scene.getPhysicsEngine();
  81837. if (!this._physicsEngine) {
  81838. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81839. }
  81840. }
  81841. /**
  81842. * @param {Vector3} origin the origin of the explosion
  81843. * @param {number} radius the explosion radius
  81844. * @param {number} strength the explosion strength
  81845. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81846. */
  81847. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81848. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81849. if (!this._physicsEngine) {
  81850. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81851. return null;
  81852. }
  81853. var impostors = this._physicsEngine.getImpostors();
  81854. if (impostors.length === 0) {
  81855. return null;
  81856. }
  81857. var event = new PhysicsRadialExplosionEvent(this._scene);
  81858. impostors.forEach(function (impostor) {
  81859. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81860. if (!impostorForceAndContactPoint) {
  81861. return;
  81862. }
  81863. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81864. });
  81865. event.dispose(false);
  81866. return event;
  81867. };
  81868. /**
  81869. * @param {Vector3} origin the origin of the explosion
  81870. * @param {number} radius the explosion radius
  81871. * @param {number} strength the explosion strength
  81872. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81873. */
  81874. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81875. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81876. if (!this._physicsEngine) {
  81877. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81878. return null;
  81879. }
  81880. var impostors = this._physicsEngine.getImpostors();
  81881. if (impostors.length === 0) {
  81882. return null;
  81883. }
  81884. var event = new PhysicsRadialExplosionEvent(this._scene);
  81885. impostors.forEach(function (impostor) {
  81886. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81887. if (!impostorForceAndContactPoint) {
  81888. return;
  81889. }
  81890. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81891. });
  81892. event.dispose(false);
  81893. return event;
  81894. };
  81895. /**
  81896. * @param {Vector3} origin the origin of the explosion
  81897. * @param {number} radius the explosion radius
  81898. * @param {number} strength the explosion strength
  81899. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81900. */
  81901. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81902. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81903. if (!this._physicsEngine) {
  81904. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81905. return null;
  81906. }
  81907. var impostors = this._physicsEngine.getImpostors();
  81908. if (impostors.length === 0) {
  81909. return null;
  81910. }
  81911. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81912. event.dispose(false);
  81913. return event;
  81914. };
  81915. /**
  81916. * @param {Vector3} origin the origin of the updraft
  81917. * @param {number} radius the radius of the updraft
  81918. * @param {number} strength the strength of the updraft
  81919. * @param {number} height the height of the updraft
  81920. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81921. */
  81922. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81923. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81924. if (!this._physicsEngine) {
  81925. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81926. return null;
  81927. }
  81928. if (this._physicsEngine.getImpostors().length === 0) {
  81929. return null;
  81930. }
  81931. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81932. event.dispose(false);
  81933. return event;
  81934. };
  81935. /**
  81936. * @param {Vector3} origin the of the vortex
  81937. * @param {number} radius the radius of the vortex
  81938. * @param {number} strength the strength of the vortex
  81939. * @param {number} height the height of the vortex
  81940. */
  81941. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81942. if (!this._physicsEngine) {
  81943. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81944. return null;
  81945. }
  81946. if (this._physicsEngine.getImpostors().length === 0) {
  81947. return null;
  81948. }
  81949. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81950. event.dispose(false);
  81951. return event;
  81952. };
  81953. return PhysicsHelper;
  81954. }());
  81955. BABYLON.PhysicsHelper = PhysicsHelper;
  81956. /***** Radial explosion *****/
  81957. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81958. function PhysicsRadialExplosionEvent(scene) {
  81959. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81960. this._rays = [];
  81961. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81962. this._scene = scene;
  81963. }
  81964. /**
  81965. * Returns the data related to the radial explosion event (sphere & rays).
  81966. * @returns {PhysicsRadialExplosionEventData}
  81967. */
  81968. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81969. this._dataFetched = true;
  81970. return {
  81971. sphere: this._sphere,
  81972. rays: this._rays,
  81973. };
  81974. };
  81975. /**
  81976. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81977. * @param impostor
  81978. * @param {Vector3} origin the origin of the explosion
  81979. * @param {number} radius the explosion radius
  81980. * @param {number} strength the explosion strength
  81981. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81982. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81983. */
  81984. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81985. if (impostor.mass === 0) {
  81986. return null;
  81987. }
  81988. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81989. return null;
  81990. }
  81991. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81992. return null;
  81993. }
  81994. var impostorObjectCenter = impostor.getObjectCenter();
  81995. var direction = impostorObjectCenter.subtract(origin);
  81996. var ray = new BABYLON.Ray(origin, direction, radius);
  81997. this._rays.push(ray);
  81998. var hit = ray.intersectsMesh(impostor.object);
  81999. var contactPoint = hit.pickedPoint;
  82000. if (!contactPoint) {
  82001. return null;
  82002. }
  82003. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82004. if (distanceFromOrigin > radius) {
  82005. return null;
  82006. }
  82007. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82008. ? strength
  82009. : strength * (1 - (distanceFromOrigin / radius));
  82010. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82011. return { force: force, contactPoint: contactPoint };
  82012. };
  82013. /**
  82014. * Disposes the sphere.
  82015. * @param {bolean} force
  82016. */
  82017. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82018. var _this = this;
  82019. if (force === void 0) { force = true; }
  82020. if (force) {
  82021. this._sphere.dispose();
  82022. }
  82023. else {
  82024. setTimeout(function () {
  82025. if (!_this._dataFetched) {
  82026. _this._sphere.dispose();
  82027. }
  82028. }, 0);
  82029. }
  82030. };
  82031. /*** Helpers ***/
  82032. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82033. if (!this._sphere) {
  82034. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82035. this._sphere.isVisible = false;
  82036. }
  82037. };
  82038. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82039. var impostorObject = impostor.object;
  82040. this._prepareSphere();
  82041. this._sphere.position = origin;
  82042. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82043. this._sphere._updateBoundingInfo();
  82044. this._sphere.computeWorldMatrix(true);
  82045. return this._sphere.intersectsMesh(impostorObject, true);
  82046. };
  82047. return PhysicsRadialExplosionEvent;
  82048. }());
  82049. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82050. /***** Gravitational Field *****/
  82051. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82052. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82053. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82054. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82055. this._physicsHelper = physicsHelper;
  82056. this._scene = scene;
  82057. this._origin = origin;
  82058. this._radius = radius;
  82059. this._strength = strength;
  82060. this._falloff = falloff;
  82061. this._tickCallback = this._tick.bind(this);
  82062. }
  82063. /**
  82064. * Returns the data related to the gravitational field event (sphere).
  82065. * @returns {PhysicsGravitationalFieldEventData}
  82066. */
  82067. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82068. this._dataFetched = true;
  82069. return {
  82070. sphere: this._sphere,
  82071. };
  82072. };
  82073. /**
  82074. * Enables the gravitational field.
  82075. */
  82076. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82077. this._tickCallback.call(this);
  82078. this._scene.registerBeforeRender(this._tickCallback);
  82079. };
  82080. /**
  82081. * Disables the gravitational field.
  82082. */
  82083. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82084. this._scene.unregisterBeforeRender(this._tickCallback);
  82085. };
  82086. /**
  82087. * Disposes the sphere.
  82088. * @param {bolean} force
  82089. */
  82090. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82091. var _this = this;
  82092. if (force === void 0) { force = true; }
  82093. if (force) {
  82094. this._sphere.dispose();
  82095. }
  82096. else {
  82097. setTimeout(function () {
  82098. if (!_this._dataFetched) {
  82099. _this._sphere.dispose();
  82100. }
  82101. }, 0);
  82102. }
  82103. };
  82104. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82105. // Since the params won't change, we fetch the event only once
  82106. if (this._sphere) {
  82107. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82108. }
  82109. else {
  82110. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82111. if (radialExplosionEvent) {
  82112. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82113. }
  82114. }
  82115. };
  82116. return PhysicsGravitationalFieldEvent;
  82117. }());
  82118. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82119. /***** Updraft *****/
  82120. var PhysicsUpdraftEvent = /** @class */ (function () {
  82121. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82122. this._scene = _scene;
  82123. this._origin = _origin;
  82124. this._radius = _radius;
  82125. this._strength = _strength;
  82126. this._height = _height;
  82127. this._updraftMode = _updraftMode;
  82128. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82129. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82130. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82131. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82132. this._physicsEngine = this._scene.getPhysicsEngine();
  82133. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82134. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82135. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82136. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82137. }
  82138. this._tickCallback = this._tick.bind(this);
  82139. }
  82140. /**
  82141. * Returns the data related to the updraft event (cylinder).
  82142. * @returns {PhysicsUpdraftEventData}
  82143. */
  82144. PhysicsUpdraftEvent.prototype.getData = function () {
  82145. this._dataFetched = true;
  82146. return {
  82147. cylinder: this._cylinder,
  82148. };
  82149. };
  82150. /**
  82151. * Enables the updraft.
  82152. */
  82153. PhysicsUpdraftEvent.prototype.enable = function () {
  82154. this._tickCallback.call(this);
  82155. this._scene.registerBeforeRender(this._tickCallback);
  82156. };
  82157. /**
  82158. * Disables the cortex.
  82159. */
  82160. PhysicsUpdraftEvent.prototype.disable = function () {
  82161. this._scene.unregisterBeforeRender(this._tickCallback);
  82162. };
  82163. /**
  82164. * Disposes the sphere.
  82165. * @param {bolean} force
  82166. */
  82167. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82168. var _this = this;
  82169. if (force === void 0) { force = true; }
  82170. if (force) {
  82171. this._cylinder.dispose();
  82172. }
  82173. else {
  82174. setTimeout(function () {
  82175. if (!_this._dataFetched) {
  82176. _this._cylinder.dispose();
  82177. }
  82178. }, 0);
  82179. }
  82180. };
  82181. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82182. if (impostor.mass === 0) {
  82183. return null;
  82184. }
  82185. if (!this._intersectsWithCylinder(impostor)) {
  82186. return null;
  82187. }
  82188. var impostorObjectCenter = impostor.getObjectCenter();
  82189. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82190. var direction = this._originDirection;
  82191. }
  82192. else {
  82193. var direction = impostorObjectCenter.subtract(this._originTop);
  82194. }
  82195. var multiplier = this._strength * -1;
  82196. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82197. return { force: force, contactPoint: impostorObjectCenter };
  82198. };
  82199. PhysicsUpdraftEvent.prototype._tick = function () {
  82200. var _this = this;
  82201. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82202. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82203. if (!impostorForceAndContactPoint) {
  82204. return;
  82205. }
  82206. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82207. });
  82208. };
  82209. /*** Helpers ***/
  82210. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82211. if (!this._cylinder) {
  82212. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82213. height: this._height,
  82214. diameter: this._radius * 2,
  82215. }, this._scene);
  82216. this._cylinder.isVisible = false;
  82217. }
  82218. };
  82219. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82220. var impostorObject = impostor.object;
  82221. this._prepareCylinder();
  82222. this._cylinder.position = this._cylinderPosition;
  82223. return this._cylinder.intersectsMesh(impostorObject, true);
  82224. };
  82225. return PhysicsUpdraftEvent;
  82226. }());
  82227. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82228. /***** Vortex *****/
  82229. var PhysicsVortexEvent = /** @class */ (function () {
  82230. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82231. this._scene = _scene;
  82232. this._origin = _origin;
  82233. this._radius = _radius;
  82234. this._strength = _strength;
  82235. this._height = _height;
  82236. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82237. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82238. this._updraftMultiplier = 0.02;
  82239. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82240. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82241. this._physicsEngine = this._scene.getPhysicsEngine();
  82242. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82243. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82244. this._tickCallback = this._tick.bind(this);
  82245. }
  82246. /**
  82247. * Returns the data related to the vortex event (cylinder).
  82248. * @returns {PhysicsVortexEventData}
  82249. */
  82250. PhysicsVortexEvent.prototype.getData = function () {
  82251. this._dataFetched = true;
  82252. return {
  82253. cylinder: this._cylinder,
  82254. };
  82255. };
  82256. /**
  82257. * Enables the vortex.
  82258. */
  82259. PhysicsVortexEvent.prototype.enable = function () {
  82260. this._tickCallback.call(this);
  82261. this._scene.registerBeforeRender(this._tickCallback);
  82262. };
  82263. /**
  82264. * Disables the cortex.
  82265. */
  82266. PhysicsVortexEvent.prototype.disable = function () {
  82267. this._scene.unregisterBeforeRender(this._tickCallback);
  82268. };
  82269. /**
  82270. * Disposes the sphere.
  82271. * @param {bolean} force
  82272. */
  82273. PhysicsVortexEvent.prototype.dispose = function (force) {
  82274. var _this = this;
  82275. if (force === void 0) { force = true; }
  82276. if (force) {
  82277. this._cylinder.dispose();
  82278. }
  82279. else {
  82280. setTimeout(function () {
  82281. if (!_this._dataFetched) {
  82282. _this._cylinder.dispose();
  82283. }
  82284. }, 0);
  82285. }
  82286. };
  82287. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82288. if (impostor.mass === 0) {
  82289. return null;
  82290. }
  82291. if (!this._intersectsWithCylinder(impostor)) {
  82292. return null;
  82293. }
  82294. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82295. return null;
  82296. }
  82297. var impostorObjectCenter = impostor.getObjectCenter();
  82298. 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)
  82299. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82300. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82301. var hit = ray.intersectsMesh(impostor.object);
  82302. var contactPoint = hit.pickedPoint;
  82303. if (!contactPoint) {
  82304. return null;
  82305. }
  82306. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82307. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82308. var directionToOrigin = contactPoint.normalize();
  82309. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82310. directionToOrigin = directionToOrigin.negate();
  82311. }
  82312. // TODO: find a more physically based solution
  82313. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82314. var forceX = directionToOrigin.x * this._strength / 8;
  82315. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82316. var forceZ = directionToOrigin.z * this._strength / 8;
  82317. }
  82318. else {
  82319. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82320. var forceY = this._originTop.y * this._updraftMultiplier;
  82321. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82322. }
  82323. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82324. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82325. return { force: force, contactPoint: impostorObjectCenter };
  82326. };
  82327. PhysicsVortexEvent.prototype._tick = function () {
  82328. var _this = this;
  82329. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82330. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82331. if (!impostorForceAndContactPoint) {
  82332. return;
  82333. }
  82334. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82335. });
  82336. };
  82337. /*** Helpers ***/
  82338. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82339. if (!this._cylinder) {
  82340. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82341. height: this._height,
  82342. diameter: this._radius * 2,
  82343. }, this._scene);
  82344. this._cylinder.isVisible = false;
  82345. }
  82346. };
  82347. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82348. var impostorObject = impostor.object;
  82349. this._prepareCylinder();
  82350. this._cylinder.position = this._cylinderPosition;
  82351. return this._cylinder.intersectsMesh(impostorObject, true);
  82352. };
  82353. return PhysicsVortexEvent;
  82354. }());
  82355. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82356. /***** Enums *****/
  82357. /**
  82358. * The strenght of the force in correspondence to the distance of the affected object
  82359. */
  82360. var PhysicsRadialImpulseFalloff;
  82361. (function (PhysicsRadialImpulseFalloff) {
  82362. /** Defines that impulse is constant in strength across it's whole radius */
  82363. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82364. /** DEfines that impulse gets weaker if it's further from the origin */
  82365. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82366. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82367. /**
  82368. * The strenght of the force in correspondence to the distance of the affected object
  82369. */
  82370. var PhysicsUpdraftMode;
  82371. (function (PhysicsUpdraftMode) {
  82372. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82373. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82374. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82375. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82376. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82377. })(BABYLON || (BABYLON = {}));
  82378. //# sourceMappingURL=babylon.physicsHelper.js.map
  82379. var BABYLON;
  82380. (function (BABYLON) {
  82381. var CannonJSPlugin = /** @class */ (function () {
  82382. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82383. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82384. if (iterations === void 0) { iterations = 10; }
  82385. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82386. this.name = "CannonJSPlugin";
  82387. this._physicsMaterials = new Array();
  82388. this._fixedTimeStep = 1 / 60;
  82389. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82390. this.BJSCANNON = CANNON;
  82391. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82392. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82393. this._tmpPosition = BABYLON.Vector3.Zero();
  82394. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82395. this._tmpUnityRotation = new BABYLON.Quaternion();
  82396. if (!this.isSupported()) {
  82397. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82398. return;
  82399. }
  82400. this._extendNamespace();
  82401. this.world = new this.BJSCANNON.World();
  82402. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82403. this.world.solver.iterations = iterations;
  82404. }
  82405. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82406. this.world.gravity.copy(gravity);
  82407. };
  82408. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82409. this._fixedTimeStep = timeStep;
  82410. };
  82411. CannonJSPlugin.prototype.getTimeStep = function () {
  82412. return this._fixedTimeStep;
  82413. };
  82414. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82415. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82416. };
  82417. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82418. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82419. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82420. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82421. };
  82422. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82423. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82424. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82425. impostor.physicsBody.applyForce(impulse, worldPoint);
  82426. };
  82427. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82428. //parent-child relationship. Does this impostor has a parent impostor?
  82429. if (impostor.parent) {
  82430. if (impostor.physicsBody) {
  82431. this.removePhysicsBody(impostor);
  82432. //TODO is that needed?
  82433. impostor.forceUpdate();
  82434. }
  82435. return;
  82436. }
  82437. //should a new body be created for this impostor?
  82438. if (impostor.isBodyInitRequired()) {
  82439. var shape = this._createShape(impostor);
  82440. //unregister events, if body is being changed
  82441. var oldBody = impostor.physicsBody;
  82442. if (oldBody) {
  82443. this.removePhysicsBody(impostor);
  82444. }
  82445. //create the body and material
  82446. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82447. var bodyCreationObject = {
  82448. mass: impostor.getParam("mass"),
  82449. material: material
  82450. };
  82451. // A simple extend, in case native options were used.
  82452. var nativeOptions = impostor.getParam("nativeOptions");
  82453. for (var key in nativeOptions) {
  82454. if (nativeOptions.hasOwnProperty(key)) {
  82455. bodyCreationObject[key] = nativeOptions[key];
  82456. }
  82457. }
  82458. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82459. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82460. this.world.addEventListener("preStep", impostor.beforeStep);
  82461. this.world.addEventListener("postStep", impostor.afterStep);
  82462. impostor.physicsBody.addShape(shape);
  82463. this.world.add(impostor.physicsBody);
  82464. //try to keep the body moving in the right direction by taking old properties.
  82465. //Should be tested!
  82466. if (oldBody) {
  82467. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82468. impostor.physicsBody[param].copy(oldBody[param]);
  82469. });
  82470. }
  82471. this._processChildMeshes(impostor);
  82472. }
  82473. //now update the body's transformation
  82474. this._updatePhysicsBodyTransformation(impostor);
  82475. };
  82476. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82477. var _this = this;
  82478. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82479. var currentRotation = mainImpostor.object.rotationQuaternion;
  82480. if (meshChildren.length) {
  82481. var processMesh = function (localPosition, mesh) {
  82482. if (!currentRotation || !mesh.rotationQuaternion) {
  82483. return;
  82484. }
  82485. var childImpostor = mesh.getPhysicsImpostor();
  82486. if (childImpostor) {
  82487. var parent = childImpostor.parent;
  82488. if (parent !== mainImpostor) {
  82489. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82490. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82491. if (childImpostor.physicsBody) {
  82492. _this.removePhysicsBody(childImpostor);
  82493. childImpostor.physicsBody = null;
  82494. }
  82495. childImpostor.parent = mainImpostor;
  82496. childImpostor.resetUpdateFlags();
  82497. 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));
  82498. //Add the mass of the children.
  82499. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82500. }
  82501. }
  82502. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82503. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82504. };
  82505. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82506. }
  82507. };
  82508. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82509. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82510. this.world.removeEventListener("preStep", impostor.beforeStep);
  82511. this.world.removeEventListener("postStep", impostor.afterStep);
  82512. this.world.remove(impostor.physicsBody);
  82513. };
  82514. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82515. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82516. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82517. if (!mainBody || !connectedBody) {
  82518. return;
  82519. }
  82520. var constraint;
  82521. var jointData = impostorJoint.joint.jointData;
  82522. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82523. var constraintData = {
  82524. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82525. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82526. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82527. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82528. maxForce: jointData.nativeParams.maxForce,
  82529. collideConnected: !!jointData.collision
  82530. };
  82531. switch (impostorJoint.joint.type) {
  82532. case BABYLON.PhysicsJoint.HingeJoint:
  82533. case BABYLON.PhysicsJoint.Hinge2Joint:
  82534. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82535. break;
  82536. case BABYLON.PhysicsJoint.DistanceJoint:
  82537. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82538. break;
  82539. case BABYLON.PhysicsJoint.SpringJoint:
  82540. var springData = jointData;
  82541. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82542. restLength: springData.length,
  82543. stiffness: springData.stiffness,
  82544. damping: springData.damping,
  82545. localAnchorA: constraintData.pivotA,
  82546. localAnchorB: constraintData.pivotB
  82547. });
  82548. break;
  82549. case BABYLON.PhysicsJoint.LockJoint:
  82550. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82551. break;
  82552. case BABYLON.PhysicsJoint.PointToPointJoint:
  82553. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82554. default:
  82555. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82556. break;
  82557. }
  82558. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82559. constraint.collideConnected = !!jointData.collision;
  82560. impostorJoint.joint.physicsJoint = constraint;
  82561. //don't add spring as constraint, as it is not one.
  82562. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  82563. this.world.addConstraint(constraint);
  82564. }
  82565. else {
  82566. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  82567. constraint.applyForce();
  82568. });
  82569. }
  82570. };
  82571. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82572. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  82573. };
  82574. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  82575. var index;
  82576. var mat;
  82577. for (index = 0; index < this._physicsMaterials.length; index++) {
  82578. mat = this._physicsMaterials[index];
  82579. if (mat.friction === friction && mat.restitution === restitution) {
  82580. return mat;
  82581. }
  82582. }
  82583. var currentMat = new this.BJSCANNON.Material(name);
  82584. currentMat.friction = friction;
  82585. currentMat.restitution = restitution;
  82586. this._physicsMaterials.push(currentMat);
  82587. return currentMat;
  82588. };
  82589. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82590. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82591. };
  82592. CannonJSPlugin.prototype._createShape = function (impostor) {
  82593. var object = impostor.object;
  82594. var returnValue;
  82595. var extendSize = impostor.getObjectExtendSize();
  82596. switch (impostor.type) {
  82597. case BABYLON.PhysicsImpostor.SphereImpostor:
  82598. var radiusX = extendSize.x;
  82599. var radiusY = extendSize.y;
  82600. var radiusZ = extendSize.z;
  82601. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82602. break;
  82603. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82604. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82605. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82606. break;
  82607. case BABYLON.PhysicsImpostor.BoxImpostor:
  82608. var box = extendSize.scale(0.5);
  82609. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82610. break;
  82611. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82612. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82613. returnValue = new this.BJSCANNON.Plane();
  82614. break;
  82615. case BABYLON.PhysicsImpostor.MeshImpostor:
  82616. // should transform the vertex data to world coordinates!!
  82617. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82618. var rawFaces = object.getIndices ? object.getIndices() : [];
  82619. if (!rawVerts)
  82620. return;
  82621. // get only scale! so the object could transform correctly.
  82622. var oldPosition = object.position.clone();
  82623. var oldRotation = object.rotation && object.rotation.clone();
  82624. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82625. object.position.copyFromFloats(0, 0, 0);
  82626. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82627. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82628. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82629. var transform = object.computeWorldMatrix(true);
  82630. // convert rawVerts to object space
  82631. var temp = new Array();
  82632. var index;
  82633. for (index = 0; index < rawVerts.length; index += 3) {
  82634. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82635. }
  82636. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82637. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82638. //now set back the transformation!
  82639. object.position.copyFrom(oldPosition);
  82640. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82641. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82642. break;
  82643. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82644. var oldPosition2 = object.position.clone();
  82645. var oldRotation2 = object.rotation && object.rotation.clone();
  82646. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82647. object.position.copyFromFloats(0, 0, 0);
  82648. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82649. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82650. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82651. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82652. returnValue = this._createHeightmap(object);
  82653. object.position.copyFrom(oldPosition2);
  82654. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82655. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82656. object.computeWorldMatrix(true);
  82657. break;
  82658. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82659. returnValue = new this.BJSCANNON.Particle();
  82660. break;
  82661. }
  82662. return returnValue;
  82663. };
  82664. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82665. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82666. var transform = object.computeWorldMatrix(true);
  82667. // convert rawVerts to object space
  82668. var temp = new Array();
  82669. var index;
  82670. for (index = 0; index < pos.length; index += 3) {
  82671. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82672. }
  82673. pos = temp;
  82674. var matrix = new Array();
  82675. //For now pointDepth will not be used and will be automatically calculated.
  82676. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82677. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82678. var boundingInfo = object.getBoundingInfo();
  82679. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82680. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82681. var elementSize = dim * 2 / arraySize;
  82682. for (var i = 0; i < pos.length; i = i + 3) {
  82683. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82684. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82685. var y = -pos[i + 2] + minY;
  82686. if (!matrix[x]) {
  82687. matrix[x] = [];
  82688. }
  82689. if (!matrix[x][z]) {
  82690. matrix[x][z] = y;
  82691. }
  82692. matrix[x][z] = Math.max(y, matrix[x][z]);
  82693. }
  82694. for (var x = 0; x <= arraySize; ++x) {
  82695. if (!matrix[x]) {
  82696. var loc = 1;
  82697. while (!matrix[(x + loc) % arraySize]) {
  82698. loc++;
  82699. }
  82700. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82701. //console.log("missing x", x);
  82702. }
  82703. for (var z = 0; z <= arraySize; ++z) {
  82704. if (!matrix[x][z]) {
  82705. var loc = 1;
  82706. var newValue;
  82707. while (newValue === undefined) {
  82708. newValue = matrix[x][(z + loc++) % arraySize];
  82709. }
  82710. matrix[x][z] = newValue;
  82711. }
  82712. }
  82713. }
  82714. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82715. elementSize: elementSize
  82716. });
  82717. //For future reference, needed for body transformation
  82718. shape.minY = minY;
  82719. return shape;
  82720. };
  82721. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82722. var object = impostor.object;
  82723. //make sure it is updated...
  82724. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82725. // The delta between the mesh position and the mesh bounding box center
  82726. var bInfo = object.getBoundingInfo();
  82727. if (!bInfo)
  82728. return;
  82729. var center = impostor.getObjectCenter();
  82730. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82731. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82732. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82733. this._tmpPosition.copyFrom(center);
  82734. var quaternion = object.rotationQuaternion;
  82735. if (!quaternion) {
  82736. return;
  82737. }
  82738. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82739. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82740. //-90 DEG in X, precalculated
  82741. quaternion = quaternion.multiply(this._minus90X);
  82742. //Invert! (Precalculated, 90 deg in X)
  82743. //No need to clone. this will never change.
  82744. impostor.setDeltaRotation(this._plus90X);
  82745. }
  82746. //If it is a heightfield, if should be centered.
  82747. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82748. var mesh = object;
  82749. var boundingInfo = mesh.getBoundingInfo();
  82750. //calculate the correct body position:
  82751. var rotationQuaternion = mesh.rotationQuaternion;
  82752. mesh.rotationQuaternion = this._tmpUnityRotation;
  82753. mesh.computeWorldMatrix(true);
  82754. //get original center with no rotation
  82755. var c = center.clone();
  82756. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82757. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82758. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82759. mesh.setPreTransformMatrix(p);
  82760. mesh.computeWorldMatrix(true);
  82761. //calculate the translation
  82762. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82763. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82764. //add it inverted to the delta
  82765. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82766. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82767. //rotation is back
  82768. mesh.rotationQuaternion = rotationQuaternion;
  82769. mesh.setPreTransformMatrix(oldPivot);
  82770. mesh.computeWorldMatrix(true);
  82771. }
  82772. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82773. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82774. //this._tmpPosition.copyFrom(object.position);
  82775. }
  82776. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82777. //Now update the impostor object
  82778. impostor.physicsBody.position.copy(this._tmpPosition);
  82779. impostor.physicsBody.quaternion.copy(quaternion);
  82780. };
  82781. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82782. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82783. if (impostor.object.rotationQuaternion) {
  82784. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82785. }
  82786. };
  82787. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82788. impostor.physicsBody.position.copy(newPosition);
  82789. impostor.physicsBody.quaternion.copy(newRotation);
  82790. };
  82791. CannonJSPlugin.prototype.isSupported = function () {
  82792. return this.BJSCANNON !== undefined;
  82793. };
  82794. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82795. impostor.physicsBody.velocity.copy(velocity);
  82796. };
  82797. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82798. impostor.physicsBody.angularVelocity.copy(velocity);
  82799. };
  82800. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82801. var v = impostor.physicsBody.velocity;
  82802. if (!v) {
  82803. return null;
  82804. }
  82805. return new BABYLON.Vector3(v.x, v.y, v.z);
  82806. };
  82807. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82808. var v = impostor.physicsBody.angularVelocity;
  82809. if (!v) {
  82810. return null;
  82811. }
  82812. return new BABYLON.Vector3(v.x, v.y, v.z);
  82813. };
  82814. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82815. impostor.physicsBody.mass = mass;
  82816. impostor.physicsBody.updateMassProperties();
  82817. };
  82818. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82819. return impostor.physicsBody.mass;
  82820. };
  82821. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82822. return impostor.physicsBody.material.friction;
  82823. };
  82824. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82825. impostor.physicsBody.material.friction = friction;
  82826. };
  82827. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82828. return impostor.physicsBody.material.restitution;
  82829. };
  82830. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82831. impostor.physicsBody.material.restitution = restitution;
  82832. };
  82833. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82834. impostor.physicsBody.sleep();
  82835. };
  82836. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82837. impostor.physicsBody.wakeUp();
  82838. };
  82839. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82840. joint.physicsJoint.distance = maxDistance;
  82841. };
  82842. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82843. // if (!motorIndex) {
  82844. // joint.physicsJoint.enableMotor();
  82845. // }
  82846. // }
  82847. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82848. // if (!motorIndex) {
  82849. // joint.physicsJoint.disableMotor();
  82850. // }
  82851. // }
  82852. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82853. if (!motorIndex) {
  82854. joint.physicsJoint.enableMotor();
  82855. joint.physicsJoint.setMotorSpeed(speed);
  82856. if (maxForce) {
  82857. this.setLimit(joint, maxForce);
  82858. }
  82859. }
  82860. };
  82861. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82862. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82863. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82864. };
  82865. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82866. var body = impostor.physicsBody;
  82867. mesh.position.x = body.position.x;
  82868. mesh.position.y = body.position.y;
  82869. mesh.position.z = body.position.z;
  82870. if (mesh.rotationQuaternion) {
  82871. mesh.rotationQuaternion.x = body.quaternion.x;
  82872. mesh.rotationQuaternion.y = body.quaternion.y;
  82873. mesh.rotationQuaternion.z = body.quaternion.z;
  82874. mesh.rotationQuaternion.w = body.quaternion.w;
  82875. }
  82876. };
  82877. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82878. var shape = impostor.physicsBody.shapes[0];
  82879. return shape.boundingSphereRadius;
  82880. };
  82881. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82882. var shape = impostor.physicsBody.shapes[0];
  82883. result.x = shape.halfExtents.x * 2;
  82884. result.y = shape.halfExtents.y * 2;
  82885. result.z = shape.halfExtents.z * 2;
  82886. };
  82887. CannonJSPlugin.prototype.dispose = function () {
  82888. };
  82889. CannonJSPlugin.prototype._extendNamespace = function () {
  82890. //this will force cannon to execute at least one step when using interpolation
  82891. var step_tmp1 = new this.BJSCANNON.Vec3();
  82892. var Engine = this.BJSCANNON;
  82893. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82894. maxSubSteps = maxSubSteps || 10;
  82895. timeSinceLastCalled = timeSinceLastCalled || 0;
  82896. if (timeSinceLastCalled === 0) {
  82897. this.internalStep(dt);
  82898. this.time += dt;
  82899. }
  82900. else {
  82901. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82902. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82903. var t0 = performance.now();
  82904. for (var i = 0; i !== internalSteps; i++) {
  82905. this.internalStep(dt);
  82906. if (performance.now() - t0 > dt * 1000) {
  82907. break;
  82908. }
  82909. }
  82910. this.time += timeSinceLastCalled;
  82911. var h = this.time % dt;
  82912. var h_div_dt = h / dt;
  82913. var interpvelo = step_tmp1;
  82914. var bodies = this.bodies;
  82915. for (var j = 0; j !== bodies.length; j++) {
  82916. var b = bodies[j];
  82917. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82918. b.position.vsub(b.previousPosition, interpvelo);
  82919. interpvelo.scale(h_div_dt, interpvelo);
  82920. b.position.vadd(interpvelo, b.interpolatedPosition);
  82921. }
  82922. else {
  82923. b.interpolatedPosition.copy(b.position);
  82924. b.interpolatedQuaternion.copy(b.quaternion);
  82925. }
  82926. }
  82927. }
  82928. };
  82929. };
  82930. return CannonJSPlugin;
  82931. }());
  82932. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82933. })(BABYLON || (BABYLON = {}));
  82934. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82935. var BABYLON;
  82936. (function (BABYLON) {
  82937. var OimoJSPlugin = /** @class */ (function () {
  82938. function OimoJSPlugin(iterations) {
  82939. this.name = "OimoJSPlugin";
  82940. this._tmpImpostorsArray = [];
  82941. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82942. this.BJSOIMO = OIMO;
  82943. this.world = new this.BJSOIMO.World({
  82944. iterations: iterations
  82945. });
  82946. this.world.clear();
  82947. }
  82948. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82949. this.world.gravity.copy(gravity);
  82950. };
  82951. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82952. this.world.timeStep = timeStep;
  82953. };
  82954. OimoJSPlugin.prototype.getTimeStep = function () {
  82955. return this.world.timeStep;
  82956. };
  82957. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82958. var _this = this;
  82959. impostors.forEach(function (impostor) {
  82960. impostor.beforeStep();
  82961. });
  82962. this.world.step();
  82963. impostors.forEach(function (impostor) {
  82964. impostor.afterStep();
  82965. //update the ordered impostors array
  82966. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82967. });
  82968. //check for collisions
  82969. var contact = this.world.contacts;
  82970. while (contact !== null) {
  82971. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82972. contact = contact.next;
  82973. continue;
  82974. }
  82975. //is this body colliding with any other? get the impostor
  82976. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82977. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82978. if (!mainImpostor || !collidingImpostor) {
  82979. contact = contact.next;
  82980. continue;
  82981. }
  82982. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82983. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82984. contact = contact.next;
  82985. }
  82986. };
  82987. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82988. var mass = impostor.physicsBody.mass;
  82989. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82990. };
  82991. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82992. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82993. this.applyImpulse(impostor, force, contactPoint);
  82994. };
  82995. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82996. var _this = this;
  82997. //parent-child relationship. Does this impostor has a parent impostor?
  82998. if (impostor.parent) {
  82999. if (impostor.physicsBody) {
  83000. this.removePhysicsBody(impostor);
  83001. //TODO is that needed?
  83002. impostor.forceUpdate();
  83003. }
  83004. return;
  83005. }
  83006. if (impostor.isBodyInitRequired()) {
  83007. var bodyConfig = {
  83008. name: impostor.uniqueId,
  83009. //Oimo must have mass, also for static objects.
  83010. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83011. size: [],
  83012. type: [],
  83013. pos: [],
  83014. posShape: [],
  83015. rot: [],
  83016. rotShape: [],
  83017. move: impostor.getParam("mass") !== 0,
  83018. density: impostor.getParam("mass"),
  83019. friction: impostor.getParam("friction"),
  83020. restitution: impostor.getParam("restitution"),
  83021. //Supporting older versions of Oimo
  83022. world: this.world
  83023. };
  83024. var impostors = [impostor];
  83025. var addToArray = function (parent) {
  83026. if (!parent.getChildMeshes)
  83027. return;
  83028. parent.getChildMeshes().forEach(function (m) {
  83029. if (m.physicsImpostor) {
  83030. impostors.push(m.physicsImpostor);
  83031. //m.physicsImpostor._init();
  83032. }
  83033. });
  83034. };
  83035. addToArray(impostor.object);
  83036. var checkWithEpsilon_1 = function (value) {
  83037. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83038. };
  83039. impostors.forEach(function (i) {
  83040. if (!i.object.rotationQuaternion) {
  83041. return;
  83042. }
  83043. //get the correct bounding box
  83044. var oldQuaternion = i.object.rotationQuaternion;
  83045. var rot = oldQuaternion.toEulerAngles();
  83046. var extendSize = i.getObjectExtendSize();
  83047. var radToDeg = 57.295779513082320876;
  83048. if (i === impostor) {
  83049. var center = impostor.getObjectCenter();
  83050. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83051. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83052. //Can also use Array.prototype.push.apply
  83053. bodyConfig.pos.push(center.x);
  83054. bodyConfig.pos.push(center.y);
  83055. bodyConfig.pos.push(center.z);
  83056. bodyConfig.posShape.push(0, 0, 0);
  83057. //tmp solution
  83058. bodyConfig.rot.push(rot.x * radToDeg);
  83059. bodyConfig.rot.push(rot.y * radToDeg);
  83060. bodyConfig.rot.push(rot.z * radToDeg);
  83061. bodyConfig.rotShape.push(0, 0, 0);
  83062. }
  83063. else {
  83064. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83065. bodyConfig.posShape.push(localPosition.x);
  83066. bodyConfig.posShape.push(localPosition.y);
  83067. bodyConfig.posShape.push(localPosition.z);
  83068. bodyConfig.pos.push(0, 0, 0);
  83069. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83070. bodyConfig.rot.push(0);
  83071. bodyConfig.rot.push(0);
  83072. bodyConfig.rot.push(0);
  83073. bodyConfig.rotShape.push(rot.x * radToDeg);
  83074. bodyConfig.rotShape.push(rot.y * radToDeg);
  83075. bodyConfig.rotShape.push(rot.z * radToDeg);
  83076. }
  83077. // register mesh
  83078. switch (i.type) {
  83079. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83080. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83081. case BABYLON.PhysicsImpostor.SphereImpostor:
  83082. var radiusX = extendSize.x;
  83083. var radiusY = extendSize.y;
  83084. var radiusZ = extendSize.z;
  83085. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83086. bodyConfig.type.push('sphere');
  83087. //due to the way oimo works with compounds, add 3 times
  83088. bodyConfig.size.push(size);
  83089. bodyConfig.size.push(size);
  83090. bodyConfig.size.push(size);
  83091. break;
  83092. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83093. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83094. var sizeY = checkWithEpsilon_1(extendSize.y);
  83095. bodyConfig.type.push('cylinder');
  83096. bodyConfig.size.push(sizeX);
  83097. bodyConfig.size.push(sizeY);
  83098. //due to the way oimo works with compounds, add one more value.
  83099. bodyConfig.size.push(sizeY);
  83100. break;
  83101. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83102. case BABYLON.PhysicsImpostor.BoxImpostor:
  83103. default:
  83104. var sizeX = checkWithEpsilon_1(extendSize.x);
  83105. var sizeY = checkWithEpsilon_1(extendSize.y);
  83106. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83107. bodyConfig.type.push('box');
  83108. //if (i === impostor) {
  83109. bodyConfig.size.push(sizeX);
  83110. bodyConfig.size.push(sizeY);
  83111. bodyConfig.size.push(sizeZ);
  83112. //} else {
  83113. // bodyConfig.size.push(0,0,0);
  83114. //}
  83115. break;
  83116. }
  83117. //actually not needed, but hey...
  83118. i.object.rotationQuaternion = oldQuaternion;
  83119. });
  83120. impostor.physicsBody = this.world.add(bodyConfig);
  83121. }
  83122. else {
  83123. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83124. }
  83125. impostor.setDeltaPosition(this._tmpPositionVector);
  83126. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83127. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83128. };
  83129. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83130. //impostor.physicsBody.dispose();
  83131. //Same as : (older oimo versions)
  83132. this.world.removeRigidBody(impostor.physicsBody);
  83133. };
  83134. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83135. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83136. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83137. if (!mainBody || !connectedBody) {
  83138. return;
  83139. }
  83140. var jointData = impostorJoint.joint.jointData;
  83141. var options = jointData.nativeParams || {};
  83142. var type;
  83143. var nativeJointData = {
  83144. body1: mainBody,
  83145. body2: connectedBody,
  83146. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83147. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83148. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83149. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83150. min: options.min,
  83151. max: options.max,
  83152. collision: options.collision || jointData.collision,
  83153. spring: options.spring,
  83154. //supporting older version of Oimo
  83155. world: this.world
  83156. };
  83157. switch (impostorJoint.joint.type) {
  83158. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83159. type = "jointBall";
  83160. break;
  83161. case BABYLON.PhysicsJoint.SpringJoint:
  83162. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83163. var springData = jointData;
  83164. nativeJointData.min = springData.length || nativeJointData.min;
  83165. //Max should also be set, just make sure it is at least min
  83166. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83167. case BABYLON.PhysicsJoint.DistanceJoint:
  83168. type = "jointDistance";
  83169. nativeJointData.max = jointData.maxDistance;
  83170. break;
  83171. case BABYLON.PhysicsJoint.PrismaticJoint:
  83172. type = "jointPrisme";
  83173. break;
  83174. case BABYLON.PhysicsJoint.SliderJoint:
  83175. type = "jointSlide";
  83176. break;
  83177. case BABYLON.PhysicsJoint.WheelJoint:
  83178. type = "jointWheel";
  83179. break;
  83180. case BABYLON.PhysicsJoint.HingeJoint:
  83181. default:
  83182. type = "jointHinge";
  83183. break;
  83184. }
  83185. nativeJointData.type = type;
  83186. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83187. };
  83188. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83189. //Bug in Oimo prevents us from disposing a joint in the playground
  83190. //joint.joint.physicsJoint.dispose();
  83191. //So we will bruteforce it!
  83192. try {
  83193. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83194. }
  83195. catch (e) {
  83196. BABYLON.Tools.Warn(e);
  83197. }
  83198. };
  83199. OimoJSPlugin.prototype.isSupported = function () {
  83200. return this.BJSOIMO !== undefined;
  83201. };
  83202. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83203. if (!impostor.physicsBody.sleeping) {
  83204. //TODO check that
  83205. /*if (impostor.physicsBody.shapes.next) {
  83206. var parentShape = this._getLastShape(impostor.physicsBody);
  83207. impostor.object.position.copyFrom(parentShape.position);
  83208. console.log(parentShape.position);
  83209. } else {*/
  83210. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83211. //}
  83212. if (impostor.object.rotationQuaternion) {
  83213. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83214. }
  83215. }
  83216. };
  83217. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83218. var body = impostor.physicsBody;
  83219. body.position.copy(newPosition);
  83220. body.orientation.copy(newRotation);
  83221. body.syncShapes();
  83222. body.awake();
  83223. };
  83224. /*private _getLastShape(body: any): any {
  83225. var lastShape = body.shapes;
  83226. while (lastShape.next) {
  83227. lastShape = lastShape.next;
  83228. }
  83229. return lastShape;
  83230. }*/
  83231. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83232. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83233. };
  83234. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83235. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83236. };
  83237. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83238. var v = impostor.physicsBody.linearVelocity;
  83239. if (!v) {
  83240. return null;
  83241. }
  83242. return new BABYLON.Vector3(v.x, v.y, v.z);
  83243. };
  83244. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83245. var v = impostor.physicsBody.angularVelocity;
  83246. if (!v) {
  83247. return null;
  83248. }
  83249. return new BABYLON.Vector3(v.x, v.y, v.z);
  83250. };
  83251. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83252. var staticBody = mass === 0;
  83253. //this will actually set the body's density and not its mass.
  83254. //But this is how oimo treats the mass variable.
  83255. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83256. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83257. };
  83258. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83259. return impostor.physicsBody.shapes.density;
  83260. };
  83261. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83262. return impostor.physicsBody.shapes.friction;
  83263. };
  83264. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83265. impostor.physicsBody.shapes.friction = friction;
  83266. };
  83267. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83268. return impostor.physicsBody.shapes.restitution;
  83269. };
  83270. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83271. impostor.physicsBody.shapes.restitution = restitution;
  83272. };
  83273. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83274. impostor.physicsBody.sleep();
  83275. };
  83276. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83277. impostor.physicsBody.awake();
  83278. };
  83279. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83280. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83281. if (minDistance !== void 0) {
  83282. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83283. }
  83284. };
  83285. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83286. //TODO separate rotational and transational motors.
  83287. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83288. if (motor) {
  83289. motor.setMotor(speed, maxForce);
  83290. }
  83291. };
  83292. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83293. //TODO separate rotational and transational motors.
  83294. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83295. if (motor) {
  83296. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83297. }
  83298. };
  83299. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83300. var body = impostor.physicsBody;
  83301. mesh.position.x = body.position.x;
  83302. mesh.position.y = body.position.y;
  83303. mesh.position.z = body.position.z;
  83304. if (mesh.rotationQuaternion) {
  83305. mesh.rotationQuaternion.x = body.orientation.x;
  83306. mesh.rotationQuaternion.y = body.orientation.y;
  83307. mesh.rotationQuaternion.z = body.orientation.z;
  83308. mesh.rotationQuaternion.w = body.orientation.s;
  83309. }
  83310. };
  83311. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83312. return impostor.physicsBody.shapes.radius;
  83313. };
  83314. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83315. var shape = impostor.physicsBody.shapes;
  83316. result.x = shape.halfWidth * 2;
  83317. result.y = shape.halfHeight * 2;
  83318. result.z = shape.halfDepth * 2;
  83319. };
  83320. OimoJSPlugin.prototype.dispose = function () {
  83321. this.world.clear();
  83322. };
  83323. return OimoJSPlugin;
  83324. }());
  83325. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83326. })(BABYLON || (BABYLON = {}));
  83327. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83328. var BABYLON;
  83329. (function (BABYLON) {
  83330. /*
  83331. * Based on jsTGALoader - Javascript loader for TGA file
  83332. * By Vincent Thibault
  83333. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83334. */
  83335. var TGATools = /** @class */ (function () {
  83336. function TGATools() {
  83337. }
  83338. TGATools.GetTGAHeader = function (data) {
  83339. var offset = 0;
  83340. var header = {
  83341. id_length: data[offset++],
  83342. colormap_type: data[offset++],
  83343. image_type: data[offset++],
  83344. colormap_index: data[offset++] | data[offset++] << 8,
  83345. colormap_length: data[offset++] | data[offset++] << 8,
  83346. colormap_size: data[offset++],
  83347. origin: [
  83348. data[offset++] | data[offset++] << 8,
  83349. data[offset++] | data[offset++] << 8
  83350. ],
  83351. width: data[offset++] | data[offset++] << 8,
  83352. height: data[offset++] | data[offset++] << 8,
  83353. pixel_size: data[offset++],
  83354. flags: data[offset++]
  83355. };
  83356. return header;
  83357. };
  83358. TGATools.UploadContent = function (gl, data) {
  83359. // Not enough data to contain header ?
  83360. if (data.length < 19) {
  83361. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83362. return;
  83363. }
  83364. // Read Header
  83365. var offset = 18;
  83366. var header = TGATools.GetTGAHeader(data);
  83367. // Assume it's a valid Targa file.
  83368. if (header.id_length + offset > data.length) {
  83369. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83370. return;
  83371. }
  83372. // Skip not needed data
  83373. offset += header.id_length;
  83374. var use_rle = false;
  83375. var use_pal = false;
  83376. var use_grey = false;
  83377. // Get some informations.
  83378. switch (header.image_type) {
  83379. case TGATools._TYPE_RLE_INDEXED:
  83380. use_rle = true;
  83381. case TGATools._TYPE_INDEXED:
  83382. use_pal = true;
  83383. break;
  83384. case TGATools._TYPE_RLE_RGB:
  83385. use_rle = true;
  83386. case TGATools._TYPE_RGB:
  83387. // use_rgb = true;
  83388. break;
  83389. case TGATools._TYPE_RLE_GREY:
  83390. use_rle = true;
  83391. case TGATools._TYPE_GREY:
  83392. use_grey = true;
  83393. break;
  83394. }
  83395. var pixel_data;
  83396. // var numAlphaBits = header.flags & 0xf;
  83397. var pixel_size = header.pixel_size >> 3;
  83398. var pixel_total = header.width * header.height * pixel_size;
  83399. // Read palettes
  83400. var palettes;
  83401. if (use_pal) {
  83402. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83403. }
  83404. // Read LRE
  83405. if (use_rle) {
  83406. pixel_data = new Uint8Array(pixel_total);
  83407. var c, count, i;
  83408. var localOffset = 0;
  83409. var pixels = new Uint8Array(pixel_size);
  83410. while (offset < pixel_total && localOffset < pixel_total) {
  83411. c = data[offset++];
  83412. count = (c & 0x7f) + 1;
  83413. // RLE pixels
  83414. if (c & 0x80) {
  83415. // Bind pixel tmp array
  83416. for (i = 0; i < pixel_size; ++i) {
  83417. pixels[i] = data[offset++];
  83418. }
  83419. // Copy pixel array
  83420. for (i = 0; i < count; ++i) {
  83421. pixel_data.set(pixels, localOffset + i * pixel_size);
  83422. }
  83423. localOffset += pixel_size * count;
  83424. }
  83425. // Raw pixels
  83426. else {
  83427. count *= pixel_size;
  83428. for (i = 0; i < count; ++i) {
  83429. pixel_data[localOffset + i] = data[offset++];
  83430. }
  83431. localOffset += count;
  83432. }
  83433. }
  83434. }
  83435. // RAW Pixels
  83436. else {
  83437. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83438. }
  83439. // Load to texture
  83440. var x_start, y_start, x_step, y_step, y_end, x_end;
  83441. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83442. default:
  83443. case TGATools._ORIGIN_UL:
  83444. x_start = 0;
  83445. x_step = 1;
  83446. x_end = header.width;
  83447. y_start = 0;
  83448. y_step = 1;
  83449. y_end = header.height;
  83450. break;
  83451. case TGATools._ORIGIN_BL:
  83452. x_start = 0;
  83453. x_step = 1;
  83454. x_end = header.width;
  83455. y_start = header.height - 1;
  83456. y_step = -1;
  83457. y_end = -1;
  83458. break;
  83459. case TGATools._ORIGIN_UR:
  83460. x_start = header.width - 1;
  83461. x_step = -1;
  83462. x_end = -1;
  83463. y_start = 0;
  83464. y_step = 1;
  83465. y_end = header.height;
  83466. break;
  83467. case TGATools._ORIGIN_BR:
  83468. x_start = header.width - 1;
  83469. x_step = -1;
  83470. x_end = -1;
  83471. y_start = header.height - 1;
  83472. y_step = -1;
  83473. y_end = -1;
  83474. break;
  83475. }
  83476. // Load the specify method
  83477. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83478. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83479. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83480. };
  83481. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83482. var image = pixel_data, colormap = palettes;
  83483. var width = header.width, height = header.height;
  83484. var color, i = 0, x, y;
  83485. var imageData = new Uint8Array(width * height * 4);
  83486. for (y = y_start; y !== y_end; y += y_step) {
  83487. for (x = x_start; x !== x_end; x += x_step, i++) {
  83488. color = image[i];
  83489. imageData[(x + width * y) * 4 + 3] = 255;
  83490. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83491. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83492. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83493. }
  83494. }
  83495. return imageData;
  83496. };
  83497. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83498. var image = pixel_data;
  83499. var width = header.width, height = header.height;
  83500. var color, i = 0, x, y;
  83501. var imageData = new Uint8Array(width * height * 4);
  83502. for (y = y_start; y !== y_end; y += y_step) {
  83503. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83504. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83505. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83506. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83507. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83508. imageData[(x + width * y) * 4 + 0] = r;
  83509. imageData[(x + width * y) * 4 + 1] = g;
  83510. imageData[(x + width * y) * 4 + 2] = b;
  83511. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83512. }
  83513. }
  83514. return imageData;
  83515. };
  83516. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83517. var image = pixel_data;
  83518. var width = header.width, height = header.height;
  83519. var i = 0, x, y;
  83520. var imageData = new Uint8Array(width * height * 4);
  83521. for (y = y_start; y !== y_end; y += y_step) {
  83522. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83523. imageData[(x + width * y) * 4 + 3] = 255;
  83524. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83525. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83526. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83527. }
  83528. }
  83529. return imageData;
  83530. };
  83531. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83532. var image = pixel_data;
  83533. var width = header.width, height = header.height;
  83534. var i = 0, x, y;
  83535. var imageData = new Uint8Array(width * height * 4);
  83536. for (y = y_start; y !== y_end; y += y_step) {
  83537. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83538. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83539. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83540. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83541. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83542. }
  83543. }
  83544. return imageData;
  83545. };
  83546. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83547. var image = pixel_data;
  83548. var width = header.width, height = header.height;
  83549. var color, i = 0, x, y;
  83550. var imageData = new Uint8Array(width * height * 4);
  83551. for (y = y_start; y !== y_end; y += y_step) {
  83552. for (x = x_start; x !== x_end; x += x_step, i++) {
  83553. color = image[i];
  83554. imageData[(x + width * y) * 4 + 0] = color;
  83555. imageData[(x + width * y) * 4 + 1] = color;
  83556. imageData[(x + width * y) * 4 + 2] = color;
  83557. imageData[(x + width * y) * 4 + 3] = 255;
  83558. }
  83559. }
  83560. return imageData;
  83561. };
  83562. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83563. var image = pixel_data;
  83564. var width = header.width, height = header.height;
  83565. var i = 0, x, y;
  83566. var imageData = new Uint8Array(width * height * 4);
  83567. for (y = y_start; y !== y_end; y += y_step) {
  83568. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83569. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  83570. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  83571. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83572. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  83573. }
  83574. }
  83575. return imageData;
  83576. };
  83577. //private static _TYPE_NO_DATA = 0;
  83578. TGATools._TYPE_INDEXED = 1;
  83579. TGATools._TYPE_RGB = 2;
  83580. TGATools._TYPE_GREY = 3;
  83581. TGATools._TYPE_RLE_INDEXED = 9;
  83582. TGATools._TYPE_RLE_RGB = 10;
  83583. TGATools._TYPE_RLE_GREY = 11;
  83584. TGATools._ORIGIN_MASK = 0x30;
  83585. TGATools._ORIGIN_SHIFT = 0x04;
  83586. TGATools._ORIGIN_BL = 0x00;
  83587. TGATools._ORIGIN_BR = 0x01;
  83588. TGATools._ORIGIN_UL = 0x02;
  83589. TGATools._ORIGIN_UR = 0x03;
  83590. return TGATools;
  83591. }());
  83592. BABYLON.TGATools = TGATools;
  83593. })(BABYLON || (BABYLON = {}));
  83594. //# sourceMappingURL=babylon.tga.js.map
  83595. var BABYLON;
  83596. (function (BABYLON) {
  83597. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83598. // All values and structures referenced from:
  83599. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83600. var DDS_MAGIC = 0x20534444;
  83601. var
  83602. //DDSD_CAPS = 0x1,
  83603. //DDSD_HEIGHT = 0x2,
  83604. //DDSD_WIDTH = 0x4,
  83605. //DDSD_PITCH = 0x8,
  83606. //DDSD_PIXELFORMAT = 0x1000,
  83607. DDSD_MIPMAPCOUNT = 0x20000;
  83608. //DDSD_LINEARSIZE = 0x80000,
  83609. //DDSD_DEPTH = 0x800000;
  83610. // var DDSCAPS_COMPLEX = 0x8,
  83611. // DDSCAPS_MIPMAP = 0x400000,
  83612. // DDSCAPS_TEXTURE = 0x1000;
  83613. var DDSCAPS2_CUBEMAP = 0x200;
  83614. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83615. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83616. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83617. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83618. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83619. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83620. // DDSCAPS2_VOLUME = 0x200000;
  83621. var
  83622. //DDPF_ALPHAPIXELS = 0x1,
  83623. //DDPF_ALPHA = 0x2,
  83624. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83625. //DDPF_YUV = 0x200,
  83626. DDPF_LUMINANCE = 0x20000;
  83627. function FourCCToInt32(value) {
  83628. return value.charCodeAt(0) +
  83629. (value.charCodeAt(1) << 8) +
  83630. (value.charCodeAt(2) << 16) +
  83631. (value.charCodeAt(3) << 24);
  83632. }
  83633. function Int32ToFourCC(value) {
  83634. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83635. }
  83636. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83637. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83638. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83639. var FOURCC_DX10 = FourCCToInt32("DX10");
  83640. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83641. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83642. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83643. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83644. var headerLengthInt = 31; // The header length in 32 bit ints
  83645. // Offsets into the header array
  83646. var off_magic = 0;
  83647. var off_size = 1;
  83648. var off_flags = 2;
  83649. var off_height = 3;
  83650. var off_width = 4;
  83651. var off_mipmapCount = 7;
  83652. var off_pfFlags = 20;
  83653. var off_pfFourCC = 21;
  83654. var off_RGBbpp = 22;
  83655. var off_RMask = 23;
  83656. var off_GMask = 24;
  83657. var off_BMask = 25;
  83658. var off_AMask = 26;
  83659. // var off_caps1 = 27;
  83660. var off_caps2 = 28;
  83661. // var off_caps3 = 29;
  83662. // var off_caps4 = 30;
  83663. var off_dxgiFormat = 32;
  83664. ;
  83665. var DDSTools = /** @class */ (function () {
  83666. function DDSTools() {
  83667. }
  83668. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83669. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83670. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83671. var mipmapCount = 1;
  83672. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83673. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83674. }
  83675. var fourCC = header[off_pfFourCC];
  83676. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83677. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83678. switch (fourCC) {
  83679. case FOURCC_D3DFMT_R16G16B16A16F:
  83680. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83681. break;
  83682. case FOURCC_D3DFMT_R32G32B32A32F:
  83683. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83684. break;
  83685. case FOURCC_DX10:
  83686. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83687. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83688. break;
  83689. }
  83690. }
  83691. return {
  83692. width: header[off_width],
  83693. height: header[off_height],
  83694. mipmapCount: mipmapCount,
  83695. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83696. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83697. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83698. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83699. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83700. dxgiFormat: dxgiFormat,
  83701. textureType: textureType
  83702. };
  83703. };
  83704. DDSTools._ToHalfFloat = function (value) {
  83705. if (!DDSTools._FloatView) {
  83706. DDSTools._FloatView = new Float32Array(1);
  83707. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83708. }
  83709. DDSTools._FloatView[0] = value;
  83710. var x = DDSTools._Int32View[0];
  83711. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83712. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83713. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83714. /* If zero, or denormal, or exponent underflows too much for a denormal
  83715. * half, return signed zero. */
  83716. if (e < 103) {
  83717. return bits;
  83718. }
  83719. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83720. if (e > 142) {
  83721. bits |= 0x7c00;
  83722. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83723. * not Inf, so make sure we set one mantissa bit too. */
  83724. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83725. return bits;
  83726. }
  83727. /* If exponent underflows but not too much, return a denormal */
  83728. if (e < 113) {
  83729. m |= 0x0800;
  83730. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83731. * to 1, which is OK. */
  83732. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83733. return bits;
  83734. }
  83735. bits |= ((e - 112) << 10) | (m >> 1);
  83736. bits += m & 1;
  83737. return bits;
  83738. };
  83739. DDSTools._FromHalfFloat = function (value) {
  83740. var s = (value & 0x8000) >> 15;
  83741. var e = (value & 0x7C00) >> 10;
  83742. var f = value & 0x03FF;
  83743. if (e === 0) {
  83744. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83745. }
  83746. else if (e == 0x1F) {
  83747. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83748. }
  83749. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83750. };
  83751. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83752. var destArray = new Float32Array(dataLength);
  83753. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83754. var index = 0;
  83755. for (var y = 0; y < height; y++) {
  83756. for (var x = 0; x < width; x++) {
  83757. var srcPos = (x + y * width) * 4;
  83758. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83759. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83760. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83761. if (DDSTools.StoreLODInAlphaChannel) {
  83762. destArray[index + 3] = lod;
  83763. }
  83764. else {
  83765. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83766. }
  83767. index += 4;
  83768. }
  83769. }
  83770. return destArray;
  83771. };
  83772. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83773. if (DDSTools.StoreLODInAlphaChannel) {
  83774. var destArray = new Uint16Array(dataLength);
  83775. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83776. var index = 0;
  83777. for (var y = 0; y < height; y++) {
  83778. for (var x = 0; x < width; x++) {
  83779. var srcPos = (x + y * width) * 4;
  83780. destArray[index] = srcData[srcPos];
  83781. destArray[index + 1] = srcData[srcPos + 1];
  83782. destArray[index + 2] = srcData[srcPos + 2];
  83783. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83784. index += 4;
  83785. }
  83786. }
  83787. return destArray;
  83788. }
  83789. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83790. };
  83791. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83792. if (DDSTools.StoreLODInAlphaChannel) {
  83793. var destArray = new Float32Array(dataLength);
  83794. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83795. var index = 0;
  83796. for (var y = 0; y < height; y++) {
  83797. for (var x = 0; x < width; x++) {
  83798. var srcPos = (x + y * width) * 4;
  83799. destArray[index] = srcData[srcPos];
  83800. destArray[index + 1] = srcData[srcPos + 1];
  83801. destArray[index + 2] = srcData[srcPos + 2];
  83802. destArray[index + 3] = lod;
  83803. index += 4;
  83804. }
  83805. }
  83806. return destArray;
  83807. }
  83808. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83809. };
  83810. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83811. var destArray = new Uint8Array(dataLength);
  83812. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83813. var index = 0;
  83814. for (var y = 0; y < height; y++) {
  83815. for (var x = 0; x < width; x++) {
  83816. var srcPos = (x + y * width) * 4;
  83817. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83818. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83819. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83820. if (DDSTools.StoreLODInAlphaChannel) {
  83821. destArray[index + 3] = lod;
  83822. }
  83823. else {
  83824. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83825. }
  83826. index += 4;
  83827. }
  83828. }
  83829. return destArray;
  83830. };
  83831. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83832. var destArray = new Uint8Array(dataLength);
  83833. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83834. var index = 0;
  83835. for (var y = 0; y < height; y++) {
  83836. for (var x = 0; x < width; x++) {
  83837. var srcPos = (x + y * width) * 4;
  83838. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83839. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83840. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83841. if (DDSTools.StoreLODInAlphaChannel) {
  83842. destArray[index + 3] = lod;
  83843. }
  83844. else {
  83845. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83846. }
  83847. index += 4;
  83848. }
  83849. }
  83850. return destArray;
  83851. };
  83852. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83853. var byteArray = new Uint8Array(dataLength);
  83854. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83855. var index = 0;
  83856. for (var y = 0; y < height; y++) {
  83857. for (var x = 0; x < width; x++) {
  83858. var srcPos = (x + y * width) * 4;
  83859. byteArray[index] = srcData[srcPos + rOffset];
  83860. byteArray[index + 1] = srcData[srcPos + gOffset];
  83861. byteArray[index + 2] = srcData[srcPos + bOffset];
  83862. byteArray[index + 3] = srcData[srcPos + aOffset];
  83863. index += 4;
  83864. }
  83865. }
  83866. return byteArray;
  83867. };
  83868. DDSTools._ExtractLongWordOrder = function (value) {
  83869. if (value === 0 || value === 255 || value === -16777216) {
  83870. return 0;
  83871. }
  83872. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83873. };
  83874. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83875. var byteArray = new Uint8Array(dataLength);
  83876. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83877. var index = 0;
  83878. for (var y = 0; y < height; y++) {
  83879. for (var x = 0; x < width; x++) {
  83880. var srcPos = (x + y * width) * 3;
  83881. byteArray[index] = srcData[srcPos + rOffset];
  83882. byteArray[index + 1] = srcData[srcPos + gOffset];
  83883. byteArray[index + 2] = srcData[srcPos + bOffset];
  83884. index += 3;
  83885. }
  83886. }
  83887. return byteArray;
  83888. };
  83889. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83890. var byteArray = new Uint8Array(dataLength);
  83891. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83892. var index = 0;
  83893. for (var y = 0; y < height; y++) {
  83894. for (var x = 0; x < width; x++) {
  83895. var srcPos = (x + y * width);
  83896. byteArray[index] = srcData[srcPos];
  83897. index++;
  83898. }
  83899. }
  83900. return byteArray;
  83901. };
  83902. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83903. if (lodIndex === void 0) { lodIndex = -1; }
  83904. var ext = engine.getCaps().s3tc;
  83905. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83906. var fourCC, width, height, dataLength = 0, dataOffset;
  83907. var byteArray, mipmapCount, mip;
  83908. var internalFormat = 0;
  83909. var format = 0;
  83910. var blockBytes = 1;
  83911. if (header[off_magic] !== DDS_MAGIC) {
  83912. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83913. return;
  83914. }
  83915. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83916. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83917. return;
  83918. }
  83919. if (info.isCompressed && !ext) {
  83920. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83921. return;
  83922. }
  83923. var bpp = header[off_RGBbpp];
  83924. dataOffset = header[off_size] + 4;
  83925. var computeFormats = false;
  83926. if (info.isFourCC) {
  83927. fourCC = header[off_pfFourCC];
  83928. switch (fourCC) {
  83929. case FOURCC_DXT1:
  83930. blockBytes = 8;
  83931. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83932. break;
  83933. case FOURCC_DXT3:
  83934. blockBytes = 16;
  83935. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83936. break;
  83937. case FOURCC_DXT5:
  83938. blockBytes = 16;
  83939. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83940. break;
  83941. case FOURCC_D3DFMT_R16G16B16A16F:
  83942. computeFormats = true;
  83943. break;
  83944. case FOURCC_D3DFMT_R32G32B32A32F:
  83945. computeFormats = true;
  83946. break;
  83947. case FOURCC_DX10:
  83948. // There is an additionnal header so dataOffset need to be changed
  83949. dataOffset += 5 * 4; // 5 uints
  83950. var supported = false;
  83951. switch (info.dxgiFormat) {
  83952. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83953. computeFormats = true;
  83954. supported = true;
  83955. break;
  83956. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83957. info.isRGB = true;
  83958. info.isFourCC = false;
  83959. bpp = 32;
  83960. supported = true;
  83961. break;
  83962. }
  83963. if (supported) {
  83964. break;
  83965. }
  83966. default:
  83967. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83968. return;
  83969. }
  83970. }
  83971. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83972. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83973. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83974. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83975. if (computeFormats) {
  83976. format = engine._getWebGLTextureType(info.textureType);
  83977. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83978. }
  83979. mipmapCount = 1;
  83980. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83981. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83982. }
  83983. for (var face = 0; face < faces; face++) {
  83984. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83985. width = header[off_width];
  83986. height = header[off_height];
  83987. for (mip = 0; mip < mipmapCount; ++mip) {
  83988. if (lodIndex === -1 || lodIndex === mip) {
  83989. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83990. var i = (lodIndex === -1) ? mip : 0;
  83991. if (!info.isCompressed && info.isFourCC) {
  83992. dataLength = width * height * 4;
  83993. var floatArray = null;
  83994. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  83995. if (bpp === 128) {
  83996. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83997. }
  83998. else if (bpp === 64) {
  83999. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84000. }
  84001. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84002. format = engine._getWebGLTextureType(info.textureType);
  84003. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84004. }
  84005. else {
  84006. if (bpp === 128) {
  84007. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84008. }
  84009. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84010. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84011. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84012. format = engine._getWebGLTextureType(info.textureType);
  84013. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84014. }
  84015. else { // 64
  84016. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84017. }
  84018. }
  84019. if (floatArray) {
  84020. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84021. }
  84022. }
  84023. else if (info.isRGB) {
  84024. if (bpp === 24) {
  84025. dataLength = width * height * 3;
  84026. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84027. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84028. }
  84029. else { // 32
  84030. dataLength = width * height * 4;
  84031. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84032. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84033. }
  84034. }
  84035. else if (info.isLuminance) {
  84036. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84037. var unpaddedRowSize = width;
  84038. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84039. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84040. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84041. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84042. }
  84043. else {
  84044. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84045. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84046. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84047. }
  84048. }
  84049. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84050. width *= 0.5;
  84051. height *= 0.5;
  84052. width = Math.max(1.0, width);
  84053. height = Math.max(1.0, height);
  84054. }
  84055. if (currentFace !== undefined) {
  84056. // Loading a single face
  84057. break;
  84058. }
  84059. }
  84060. };
  84061. DDSTools.StoreLODInAlphaChannel = false;
  84062. return DDSTools;
  84063. }());
  84064. BABYLON.DDSTools = DDSTools;
  84065. })(BABYLON || (BABYLON = {}));
  84066. //# sourceMappingURL=babylon.dds.js.map
  84067. var BABYLON;
  84068. (function (BABYLON) {
  84069. /**
  84070. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84071. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84072. */
  84073. var KhronosTextureContainer = /** @class */ (function () {
  84074. /**
  84075. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84076. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84077. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84078. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84079. */
  84080. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84081. this.arrayBuffer = arrayBuffer;
  84082. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84083. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84084. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84085. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84086. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84087. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84088. BABYLON.Tools.Error("texture missing KTX identifier");
  84089. return;
  84090. }
  84091. // load the reset of the header in native 32 bit int
  84092. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84093. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84094. var oppositeEndianess = header[0] === 0x01020304;
  84095. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84096. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84097. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84098. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84099. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84100. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84101. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84102. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84103. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84104. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84105. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84106. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84107. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84108. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84109. if (this.glType !== 0) {
  84110. BABYLON.Tools.Error("only compressed formats currently supported");
  84111. return;
  84112. }
  84113. else {
  84114. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84115. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84116. }
  84117. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84118. BABYLON.Tools.Error("only 2D textures currently supported");
  84119. return;
  84120. }
  84121. if (this.numberOfArrayElements !== 0) {
  84122. BABYLON.Tools.Error("texture arrays not currently supported");
  84123. return;
  84124. }
  84125. if (this.numberOfFaces !== facesExpected) {
  84126. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84127. return;
  84128. }
  84129. // we now have a completely validated file, so could use existence of loadType as success
  84130. // would need to make this more elaborate & adjust checks above to support more than one load type
  84131. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84132. }
  84133. // not as fast hardware based, but will probably never need to use
  84134. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84135. return ((val & 0xFF) << 24)
  84136. | ((val & 0xFF00) << 8)
  84137. | ((val >> 8) & 0xFF00)
  84138. | ((val >> 24) & 0xFF);
  84139. };
  84140. /**
  84141. * It is assumed that the texture has already been created & is currently bound
  84142. */
  84143. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84144. switch (this.loadType) {
  84145. case KhronosTextureContainer.COMPRESSED_2D:
  84146. this._upload2DCompressedLevels(gl, loadMipmaps);
  84147. break;
  84148. case KhronosTextureContainer.TEX_2D:
  84149. case KhronosTextureContainer.COMPRESSED_3D:
  84150. case KhronosTextureContainer.TEX_3D:
  84151. }
  84152. };
  84153. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84154. // initialize width & height for level 1
  84155. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84156. var width = this.pixelWidth;
  84157. var height = this.pixelHeight;
  84158. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84159. for (var level = 0; level < mipmapCount; level++) {
  84160. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84161. for (var face = 0; face < this.numberOfFaces; face++) {
  84162. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84163. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84164. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84165. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84166. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84167. }
  84168. width = Math.max(1.0, width * 0.5);
  84169. height = Math.max(1.0, height * 0.5);
  84170. }
  84171. };
  84172. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84173. // load types
  84174. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84175. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84176. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84177. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84178. return KhronosTextureContainer;
  84179. }());
  84180. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84181. })(BABYLON || (BABYLON = {}));
  84182. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84183. var BABYLON;
  84184. (function (BABYLON) {
  84185. var Debug;
  84186. (function (Debug) {
  84187. /**
  84188. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84189. */
  84190. var SkeletonViewer = /** @class */ (function () {
  84191. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84192. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84193. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84194. this.skeleton = skeleton;
  84195. this.mesh = mesh;
  84196. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84197. this.renderingGroupId = renderingGroupId;
  84198. this.color = BABYLON.Color3.White();
  84199. this._debugLines = new Array();
  84200. this._isEnabled = false;
  84201. this._scene = scene;
  84202. this.update();
  84203. this._renderFunction = this.update.bind(this);
  84204. }
  84205. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84206. get: function () {
  84207. return this._isEnabled;
  84208. },
  84209. set: function (value) {
  84210. if (this._isEnabled === value) {
  84211. return;
  84212. }
  84213. this._isEnabled = value;
  84214. if (value) {
  84215. this._scene.registerBeforeRender(this._renderFunction);
  84216. }
  84217. else {
  84218. this._scene.unregisterBeforeRender(this._renderFunction);
  84219. }
  84220. },
  84221. enumerable: true,
  84222. configurable: true
  84223. });
  84224. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84225. if (x === void 0) { x = 0; }
  84226. if (y === void 0) { y = 0; }
  84227. if (z === void 0) { z = 0; }
  84228. var tmat = BABYLON.Tmp.Matrix[0];
  84229. var parentBone = bone.getParent();
  84230. tmat.copyFrom(bone.getLocalMatrix());
  84231. if (x !== 0 || y !== 0 || z !== 0) {
  84232. var tmat2 = BABYLON.Tmp.Matrix[1];
  84233. BABYLON.Matrix.IdentityToRef(tmat2);
  84234. tmat2.m[12] = x;
  84235. tmat2.m[13] = y;
  84236. tmat2.m[14] = z;
  84237. tmat2.multiplyToRef(tmat, tmat);
  84238. }
  84239. if (parentBone) {
  84240. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84241. }
  84242. tmat.multiplyToRef(meshMat, tmat);
  84243. position.x = tmat.m[12];
  84244. position.y = tmat.m[13];
  84245. position.z = tmat.m[14];
  84246. };
  84247. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84248. var len = bones.length;
  84249. var meshPos = this.mesh.position;
  84250. for (var i = 0; i < len; i++) {
  84251. var bone = bones[i];
  84252. var points = this._debugLines[i];
  84253. if (!points) {
  84254. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84255. this._debugLines[i] = points;
  84256. }
  84257. this._getBonePosition(points[0], bone, meshMat);
  84258. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84259. points[0].subtractInPlace(meshPos);
  84260. points[1].subtractInPlace(meshPos);
  84261. }
  84262. };
  84263. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84264. var len = bones.length;
  84265. var boneNum = 0;
  84266. var meshPos = this.mesh.position;
  84267. for (var i = len - 1; i >= 0; i--) {
  84268. var childBone = bones[i];
  84269. var parentBone = childBone.getParent();
  84270. if (!parentBone) {
  84271. continue;
  84272. }
  84273. var points = this._debugLines[boneNum];
  84274. if (!points) {
  84275. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84276. this._debugLines[boneNum] = points;
  84277. }
  84278. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84279. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84280. points[0].subtractInPlace(meshPos);
  84281. points[1].subtractInPlace(meshPos);
  84282. boneNum++;
  84283. }
  84284. };
  84285. SkeletonViewer.prototype.update = function () {
  84286. if (this.autoUpdateBonesMatrices) {
  84287. this.skeleton.computeAbsoluteTransforms();
  84288. }
  84289. if (this.skeleton.bones[0].length === undefined) {
  84290. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84291. }
  84292. else {
  84293. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84294. }
  84295. if (!this._debugMesh) {
  84296. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84297. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84298. }
  84299. else {
  84300. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84301. }
  84302. this._debugMesh.position.copyFrom(this.mesh.position);
  84303. this._debugMesh.color = this.color;
  84304. };
  84305. SkeletonViewer.prototype.dispose = function () {
  84306. if (this._debugMesh) {
  84307. this.isEnabled = false;
  84308. this._debugMesh.dispose();
  84309. this._debugMesh = null;
  84310. }
  84311. };
  84312. return SkeletonViewer;
  84313. }());
  84314. Debug.SkeletonViewer = SkeletonViewer;
  84315. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84316. })(BABYLON || (BABYLON = {}));
  84317. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84318. /**
  84319. * Module Debug contains the (visual) components to debug a scene correctly
  84320. */
  84321. var BABYLON;
  84322. (function (BABYLON) {
  84323. var Debug;
  84324. (function (Debug) {
  84325. /**
  84326. * The Axes viewer will show 3 axes in a specific point in space
  84327. */
  84328. var AxesViewer = /** @class */ (function () {
  84329. function AxesViewer(scene, scaleLines) {
  84330. if (scaleLines === void 0) { scaleLines = 1; }
  84331. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84332. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84333. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84334. this.scaleLines = 1;
  84335. this.scaleLines = scaleLines;
  84336. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84337. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84338. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84339. this._xmesh.renderingGroupId = 2;
  84340. this._ymesh.renderingGroupId = 2;
  84341. this._zmesh.renderingGroupId = 2;
  84342. this._xmesh.material.checkReadyOnlyOnce = true;
  84343. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84344. this._ymesh.material.checkReadyOnlyOnce = true;
  84345. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84346. this._zmesh.material.checkReadyOnlyOnce = true;
  84347. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84348. this.scene = scene;
  84349. }
  84350. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84351. var scaleLines = this.scaleLines;
  84352. if (this._xmesh) {
  84353. this._xmesh.position.copyFrom(position);
  84354. }
  84355. if (this._ymesh) {
  84356. this._ymesh.position.copyFrom(position);
  84357. }
  84358. if (this._zmesh) {
  84359. this._zmesh.position.copyFrom(position);
  84360. }
  84361. var point2 = this._xline[1];
  84362. point2.x = xaxis.x * scaleLines;
  84363. point2.y = xaxis.y * scaleLines;
  84364. point2.z = xaxis.z * scaleLines;
  84365. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84366. point2 = this._yline[1];
  84367. point2.x = yaxis.x * scaleLines;
  84368. point2.y = yaxis.y * scaleLines;
  84369. point2.z = yaxis.z * scaleLines;
  84370. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84371. point2 = this._zline[1];
  84372. point2.x = zaxis.x * scaleLines;
  84373. point2.y = zaxis.y * scaleLines;
  84374. point2.z = zaxis.z * scaleLines;
  84375. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84376. };
  84377. AxesViewer.prototype.dispose = function () {
  84378. if (this._xmesh) {
  84379. this._xmesh.dispose();
  84380. }
  84381. if (this._ymesh) {
  84382. this._ymesh.dispose();
  84383. }
  84384. if (this._zmesh) {
  84385. this._zmesh.dispose();
  84386. }
  84387. this._xmesh = null;
  84388. this._ymesh = null;
  84389. this._zmesh = null;
  84390. this.scene = null;
  84391. };
  84392. return AxesViewer;
  84393. }());
  84394. Debug.AxesViewer = AxesViewer;
  84395. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84396. })(BABYLON || (BABYLON = {}));
  84397. //# sourceMappingURL=babylon.axesViewer.js.map
  84398. var BABYLON;
  84399. (function (BABYLON) {
  84400. var Debug;
  84401. (function (Debug) {
  84402. /**
  84403. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84404. */
  84405. var BoneAxesViewer = /** @class */ (function (_super) {
  84406. __extends(BoneAxesViewer, _super);
  84407. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84408. if (scaleLines === void 0) { scaleLines = 1; }
  84409. var _this = _super.call(this, scene, scaleLines) || this;
  84410. _this.pos = BABYLON.Vector3.Zero();
  84411. _this.xaxis = BABYLON.Vector3.Zero();
  84412. _this.yaxis = BABYLON.Vector3.Zero();
  84413. _this.zaxis = BABYLON.Vector3.Zero();
  84414. _this.mesh = mesh;
  84415. _this.bone = bone;
  84416. return _this;
  84417. }
  84418. BoneAxesViewer.prototype.update = function () {
  84419. if (!this.mesh || !this.bone) {
  84420. return;
  84421. }
  84422. var bone = this.bone;
  84423. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84424. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84425. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84426. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84427. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84428. };
  84429. BoneAxesViewer.prototype.dispose = function () {
  84430. if (this.mesh) {
  84431. this.mesh = null;
  84432. this.bone = null;
  84433. _super.prototype.dispose.call(this);
  84434. }
  84435. };
  84436. return BoneAxesViewer;
  84437. }(Debug.AxesViewer));
  84438. Debug.BoneAxesViewer = BoneAxesViewer;
  84439. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84440. })(BABYLON || (BABYLON = {}));
  84441. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84442. var BABYLON;
  84443. (function (BABYLON) {
  84444. var RayHelper = /** @class */ (function () {
  84445. function RayHelper(ray) {
  84446. this.ray = ray;
  84447. }
  84448. RayHelper.CreateAndShow = function (ray, scene, color) {
  84449. var helper = new RayHelper(ray);
  84450. helper.show(scene, color);
  84451. return helper;
  84452. };
  84453. RayHelper.prototype.show = function (scene, color) {
  84454. if (!this._renderFunction && this.ray) {
  84455. var ray = this.ray;
  84456. this._renderFunction = this._render.bind(this);
  84457. this._scene = scene;
  84458. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84459. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84460. if (this._renderFunction) {
  84461. this._scene.registerBeforeRender(this._renderFunction);
  84462. }
  84463. }
  84464. if (color && this._renderLine) {
  84465. this._renderLine.color.copyFrom(color);
  84466. }
  84467. };
  84468. RayHelper.prototype.hide = function () {
  84469. if (this._renderFunction && this._scene) {
  84470. this._scene.unregisterBeforeRender(this._renderFunction);
  84471. this._scene = null;
  84472. this._renderFunction = null;
  84473. if (this._renderLine) {
  84474. this._renderLine.dispose();
  84475. this._renderLine = null;
  84476. }
  84477. this._renderPoints = [];
  84478. }
  84479. };
  84480. RayHelper.prototype._render = function () {
  84481. var ray = this.ray;
  84482. if (!ray) {
  84483. return;
  84484. }
  84485. var point = this._renderPoints[1];
  84486. var len = Math.min(ray.length, 1000000);
  84487. point.copyFrom(ray.direction);
  84488. point.scaleInPlace(len);
  84489. point.addInPlace(ray.origin);
  84490. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84491. };
  84492. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84493. this._attachedToMesh = mesh;
  84494. var ray = this.ray;
  84495. if (!ray) {
  84496. return;
  84497. }
  84498. if (!ray.direction) {
  84499. ray.direction = BABYLON.Vector3.Zero();
  84500. }
  84501. if (!ray.origin) {
  84502. ray.origin = BABYLON.Vector3.Zero();
  84503. }
  84504. if (length) {
  84505. ray.length = length;
  84506. }
  84507. if (!meshSpaceOrigin) {
  84508. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84509. }
  84510. if (!meshSpaceDirection) {
  84511. // -1 so that this will work with Mesh.lookAt
  84512. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84513. }
  84514. if (!this._meshSpaceDirection) {
  84515. this._meshSpaceDirection = meshSpaceDirection.clone();
  84516. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84517. }
  84518. else {
  84519. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84520. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84521. }
  84522. if (!this._updateToMeshFunction) {
  84523. this._updateToMeshFunction = this._updateToMesh.bind(this);
  84524. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  84525. }
  84526. this._updateToMesh();
  84527. };
  84528. RayHelper.prototype.detachFromMesh = function () {
  84529. if (this._attachedToMesh) {
  84530. if (this._updateToMeshFunction) {
  84531. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  84532. }
  84533. this._attachedToMesh = null;
  84534. this._updateToMeshFunction = null;
  84535. }
  84536. };
  84537. RayHelper.prototype._updateToMesh = function () {
  84538. var ray = this.ray;
  84539. if (!this._attachedToMesh || !ray) {
  84540. return;
  84541. }
  84542. if (this._attachedToMesh._isDisposed) {
  84543. this.detachFromMesh();
  84544. return;
  84545. }
  84546. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  84547. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  84548. };
  84549. RayHelper.prototype.dispose = function () {
  84550. this.hide();
  84551. this.detachFromMesh();
  84552. this.ray = null;
  84553. };
  84554. return RayHelper;
  84555. }());
  84556. BABYLON.RayHelper = RayHelper;
  84557. })(BABYLON || (BABYLON = {}));
  84558. //# sourceMappingURL=babylon.rayHelper.js.map
  84559. var BABYLON;
  84560. (function (BABYLON) {
  84561. // load the inspector using require, if not present in the global namespace.
  84562. var DebugLayer = /** @class */ (function () {
  84563. function DebugLayer(scene) {
  84564. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84565. this._scene = scene;
  84566. // load inspector using require, if it doesn't exist on the global namespace.
  84567. }
  84568. /** Creates the inspector window. */
  84569. DebugLayer.prototype._createInspector = function (config) {
  84570. if (config === void 0) { config = {}; }
  84571. var popup = config.popup || false;
  84572. var initialTab = config.initialTab || 0;
  84573. var parentElement = config.parentElement || null;
  84574. if (!this._inspector) {
  84575. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84576. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  84577. } // else nothing to do,; instance is already existing
  84578. };
  84579. DebugLayer.prototype.isVisible = function () {
  84580. if (!this._inspector) {
  84581. return false;
  84582. }
  84583. return true;
  84584. };
  84585. DebugLayer.prototype.hide = function () {
  84586. if (this._inspector) {
  84587. try {
  84588. this._inspector.dispose();
  84589. }
  84590. catch (e) {
  84591. // If the inspector has been removed directly from the inspector tool
  84592. }
  84593. this._inspector = null;
  84594. }
  84595. };
  84596. DebugLayer.prototype.show = function (config) {
  84597. if (config === void 0) { config = {}; }
  84598. if (typeof this.BJSINSPECTOR == 'undefined') {
  84599. // Load inspector and add it to the DOM
  84600. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84601. }
  84602. else {
  84603. // Otherwise creates the inspector
  84604. this._createInspector(config);
  84605. }
  84606. };
  84607. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84608. return DebugLayer;
  84609. }());
  84610. BABYLON.DebugLayer = DebugLayer;
  84611. })(BABYLON || (BABYLON = {}));
  84612. //# sourceMappingURL=babylon.debugLayer.js.map
  84613. var BABYLON;
  84614. (function (BABYLON) {
  84615. var Debug;
  84616. (function (Debug) {
  84617. /**
  84618. * Used to show the physics impostor around the specific mesh.
  84619. */
  84620. var PhysicsViewer = /** @class */ (function () {
  84621. function PhysicsViewer(scene) {
  84622. this._impostors = [];
  84623. this._meshes = [];
  84624. this._numMeshes = 0;
  84625. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84626. var physicEngine = this._scene.getPhysicsEngine();
  84627. if (physicEngine) {
  84628. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84629. }
  84630. }
  84631. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84632. var plugin = this._physicsEnginePlugin;
  84633. for (var i = 0; i < this._numMeshes; i++) {
  84634. var impostor = this._impostors[i];
  84635. if (!impostor) {
  84636. continue;
  84637. }
  84638. if (impostor.isDisposed) {
  84639. this.hideImpostor(this._impostors[i--]);
  84640. }
  84641. else {
  84642. var mesh = this._meshes[i];
  84643. if (mesh && plugin) {
  84644. plugin.syncMeshWithImpostor(mesh, impostor);
  84645. }
  84646. }
  84647. }
  84648. };
  84649. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84650. if (!this._scene) {
  84651. return;
  84652. }
  84653. for (var i = 0; i < this._numMeshes; i++) {
  84654. if (this._impostors[i] == impostor) {
  84655. return;
  84656. }
  84657. }
  84658. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84659. if (debugMesh) {
  84660. this._impostors[this._numMeshes] = impostor;
  84661. this._meshes[this._numMeshes] = debugMesh;
  84662. if (this._numMeshes === 0) {
  84663. this._renderFunction = this._updateDebugMeshes.bind(this);
  84664. this._scene.registerBeforeRender(this._renderFunction);
  84665. }
  84666. this._numMeshes++;
  84667. }
  84668. };
  84669. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84670. if (!impostor || !this._scene) {
  84671. return;
  84672. }
  84673. var removed = false;
  84674. for (var i = 0; i < this._numMeshes; i++) {
  84675. if (this._impostors[i] == impostor) {
  84676. var mesh = this._meshes[i];
  84677. if (!mesh) {
  84678. continue;
  84679. }
  84680. this._scene.removeMesh(mesh);
  84681. mesh.dispose();
  84682. this._numMeshes--;
  84683. if (this._numMeshes > 0) {
  84684. this._meshes[i] = this._meshes[this._numMeshes];
  84685. this._impostors[i] = this._impostors[this._numMeshes];
  84686. this._meshes[this._numMeshes] = null;
  84687. this._impostors[this._numMeshes] = null;
  84688. }
  84689. else {
  84690. this._meshes[0] = null;
  84691. this._impostors[0] = null;
  84692. }
  84693. removed = true;
  84694. break;
  84695. }
  84696. }
  84697. if (removed && this._numMeshes === 0) {
  84698. this._scene.unregisterBeforeRender(this._renderFunction);
  84699. }
  84700. };
  84701. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84702. if (!this._debugMaterial) {
  84703. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84704. this._debugMaterial.wireframe = true;
  84705. }
  84706. return this._debugMaterial;
  84707. };
  84708. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84709. if (!this._debugBoxMesh) {
  84710. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84711. this._debugBoxMesh.renderingGroupId = 1;
  84712. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84713. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84714. scene.removeMesh(this._debugBoxMesh);
  84715. }
  84716. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84717. };
  84718. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84719. if (!this._debugSphereMesh) {
  84720. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84721. this._debugSphereMesh.renderingGroupId = 1;
  84722. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84723. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84724. scene.removeMesh(this._debugSphereMesh);
  84725. }
  84726. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84727. };
  84728. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84729. var mesh = null;
  84730. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84731. mesh = this._getDebugBoxMesh(scene);
  84732. impostor.getBoxSizeToRef(mesh.scaling);
  84733. }
  84734. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84735. mesh = this._getDebugSphereMesh(scene);
  84736. var radius = impostor.getRadius();
  84737. mesh.scaling.x = radius * 2;
  84738. mesh.scaling.y = radius * 2;
  84739. mesh.scaling.z = radius * 2;
  84740. }
  84741. return mesh;
  84742. };
  84743. PhysicsViewer.prototype.dispose = function () {
  84744. for (var i = 0; i < this._numMeshes; i++) {
  84745. this.hideImpostor(this._impostors[i]);
  84746. }
  84747. if (this._debugBoxMesh) {
  84748. this._debugBoxMesh.dispose();
  84749. }
  84750. if (this._debugSphereMesh) {
  84751. this._debugSphereMesh.dispose();
  84752. }
  84753. if (this._debugMaterial) {
  84754. this._debugMaterial.dispose();
  84755. }
  84756. this._impostors.length = 0;
  84757. this._scene = null;
  84758. this._physicsEnginePlugin = null;
  84759. };
  84760. return PhysicsViewer;
  84761. }());
  84762. Debug.PhysicsViewer = PhysicsViewer;
  84763. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84764. })(BABYLON || (BABYLON = {}));
  84765. //# sourceMappingURL=babylon.physicsViewer.js.map
  84766. var BABYLON;
  84767. (function (BABYLON) {
  84768. var BoundingBoxRenderer = /** @class */ (function () {
  84769. function BoundingBoxRenderer(scene) {
  84770. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84771. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84772. this.showBackLines = true;
  84773. this.renderList = new BABYLON.SmartArray(32);
  84774. this._vertexBuffers = {};
  84775. this._scene = scene;
  84776. }
  84777. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84778. if (this._colorShader) {
  84779. return;
  84780. }
  84781. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84782. attributes: [BABYLON.VertexBuffer.PositionKind],
  84783. uniforms: ["world", "viewProjection", "color"]
  84784. });
  84785. var engine = this._scene.getEngine();
  84786. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84787. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84788. this._createIndexBuffer();
  84789. };
  84790. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84791. var engine = this._scene.getEngine();
  84792. 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]);
  84793. };
  84794. BoundingBoxRenderer.prototype._rebuild = function () {
  84795. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84796. if (vb) {
  84797. vb._rebuild();
  84798. }
  84799. this._createIndexBuffer();
  84800. };
  84801. BoundingBoxRenderer.prototype.reset = function () {
  84802. this.renderList.reset();
  84803. };
  84804. BoundingBoxRenderer.prototype.render = function () {
  84805. if (this.renderList.length === 0) {
  84806. return;
  84807. }
  84808. this._prepareRessources();
  84809. if (!this._colorShader.isReady()) {
  84810. return;
  84811. }
  84812. var engine = this._scene.getEngine();
  84813. engine.setDepthWrite(false);
  84814. this._colorShader._preBind();
  84815. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84816. var boundingBox = this.renderList.data[boundingBoxIndex];
  84817. var min = boundingBox.minimum;
  84818. var max = boundingBox.maximum;
  84819. var diff = max.subtract(min);
  84820. var median = min.add(diff.scale(0.5));
  84821. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84822. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84823. .multiply(boundingBox.getWorldMatrix());
  84824. // VBOs
  84825. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84826. if (this.showBackLines) {
  84827. // Back
  84828. engine.setDepthFunctionToGreaterOrEqual();
  84829. this._scene.resetCachedMaterial();
  84830. this._colorShader.setColor4("color", this.backColor.toColor4());
  84831. this._colorShader.bind(worldMatrix);
  84832. // Draw order
  84833. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84834. }
  84835. // Front
  84836. engine.setDepthFunctionToLess();
  84837. this._scene.resetCachedMaterial();
  84838. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84839. this._colorShader.bind(worldMatrix);
  84840. // Draw order
  84841. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84842. }
  84843. this._colorShader.unbind();
  84844. engine.setDepthFunctionToLessOrEqual();
  84845. engine.setDepthWrite(true);
  84846. };
  84847. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84848. this._prepareRessources();
  84849. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84850. return;
  84851. }
  84852. var engine = this._scene.getEngine();
  84853. engine.setDepthWrite(false);
  84854. engine.setColorWrite(false);
  84855. this._colorShader._preBind();
  84856. var boundingBox = mesh._boundingInfo.boundingBox;
  84857. var min = boundingBox.minimum;
  84858. var max = boundingBox.maximum;
  84859. var diff = max.subtract(min);
  84860. var median = min.add(diff.scale(0.5));
  84861. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84862. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84863. .multiply(boundingBox.getWorldMatrix());
  84864. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84865. engine.setDepthFunctionToLess();
  84866. this._scene.resetCachedMaterial();
  84867. this._colorShader.bind(worldMatrix);
  84868. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84869. this._colorShader.unbind();
  84870. engine.setDepthFunctionToLessOrEqual();
  84871. engine.setDepthWrite(true);
  84872. engine.setColorWrite(true);
  84873. };
  84874. BoundingBoxRenderer.prototype.dispose = function () {
  84875. if (!this._colorShader) {
  84876. return;
  84877. }
  84878. this.renderList.dispose();
  84879. this._colorShader.dispose();
  84880. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84881. if (buffer) {
  84882. buffer.dispose();
  84883. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84884. }
  84885. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84886. };
  84887. return BoundingBoxRenderer;
  84888. }());
  84889. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84890. })(BABYLON || (BABYLON = {}));
  84891. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84892. var BABYLON;
  84893. (function (BABYLON) {
  84894. /**
  84895. * Defines a target to use with MorphTargetManager
  84896. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84897. */
  84898. var MorphTarget = /** @class */ (function () {
  84899. /**
  84900. * Creates a new MorphTarget
  84901. * @param name defines the name of the target
  84902. * @param influence defines the influence to use
  84903. */
  84904. function MorphTarget(
  84905. /** defines the name of the target */
  84906. name, influence) {
  84907. if (influence === void 0) { influence = 0; }
  84908. this.name = name;
  84909. /**
  84910. * Gets or sets the list of animations
  84911. */
  84912. this.animations = new Array();
  84913. this._positions = null;
  84914. this._normals = null;
  84915. this._tangents = null;
  84916. /**
  84917. * Observable raised when the influence changes
  84918. */
  84919. this.onInfluenceChanged = new BABYLON.Observable();
  84920. this.influence = influence;
  84921. }
  84922. Object.defineProperty(MorphTarget.prototype, "influence", {
  84923. /**
  84924. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84925. */
  84926. get: function () {
  84927. return this._influence;
  84928. },
  84929. set: function (influence) {
  84930. if (this._influence === influence) {
  84931. return;
  84932. }
  84933. var previous = this._influence;
  84934. this._influence = influence;
  84935. if (this.onInfluenceChanged.hasObservers) {
  84936. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84937. }
  84938. },
  84939. enumerable: true,
  84940. configurable: true
  84941. });
  84942. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84943. /**
  84944. * Gets a boolean defining if the target contains position data
  84945. */
  84946. get: function () {
  84947. return !!this._positions;
  84948. },
  84949. enumerable: true,
  84950. configurable: true
  84951. });
  84952. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84953. /**
  84954. * Gets a boolean defining if the target contains normal data
  84955. */
  84956. get: function () {
  84957. return !!this._normals;
  84958. },
  84959. enumerable: true,
  84960. configurable: true
  84961. });
  84962. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84963. /**
  84964. * Gets a boolean defining if the target contains tangent data
  84965. */
  84966. get: function () {
  84967. return !!this._tangents;
  84968. },
  84969. enumerable: true,
  84970. configurable: true
  84971. });
  84972. /**
  84973. * Affects position data to this target
  84974. * @param data defines the position data to use
  84975. */
  84976. MorphTarget.prototype.setPositions = function (data) {
  84977. this._positions = data;
  84978. };
  84979. /**
  84980. * Gets the position data stored in this target
  84981. * @returns a FloatArray containing the position data (or null if not present)
  84982. */
  84983. MorphTarget.prototype.getPositions = function () {
  84984. return this._positions;
  84985. };
  84986. /**
  84987. * Affects normal data to this target
  84988. * @param data defines the normal data to use
  84989. */
  84990. MorphTarget.prototype.setNormals = function (data) {
  84991. this._normals = data;
  84992. };
  84993. /**
  84994. * Gets the normal data stored in this target
  84995. * @returns a FloatArray containing the normal data (or null if not present)
  84996. */
  84997. MorphTarget.prototype.getNormals = function () {
  84998. return this._normals;
  84999. };
  85000. /**
  85001. * Affects tangent data to this target
  85002. * @param data defines the tangent data to use
  85003. */
  85004. MorphTarget.prototype.setTangents = function (data) {
  85005. this._tangents = data;
  85006. };
  85007. /**
  85008. * Gets the tangent data stored in this target
  85009. * @returns a FloatArray containing the tangent data (or null if not present)
  85010. */
  85011. MorphTarget.prototype.getTangents = function () {
  85012. return this._tangents;
  85013. };
  85014. /**
  85015. * Serializes the current target into a Serialization object
  85016. * @returns the serialized object
  85017. */
  85018. MorphTarget.prototype.serialize = function () {
  85019. var serializationObject = {};
  85020. serializationObject.name = this.name;
  85021. serializationObject.influence = this.influence;
  85022. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85023. if (this.hasNormals) {
  85024. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85025. }
  85026. if (this.hasTangents) {
  85027. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85028. }
  85029. // Animations
  85030. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85031. return serializationObject;
  85032. };
  85033. // Statics
  85034. /**
  85035. * Creates a new target from serialized data
  85036. * @param serializationObject defines the serialized data to use
  85037. * @returns a new MorphTarget
  85038. */
  85039. MorphTarget.Parse = function (serializationObject) {
  85040. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85041. result.setPositions(serializationObject.positions);
  85042. if (serializationObject.normals) {
  85043. result.setNormals(serializationObject.normals);
  85044. }
  85045. if (serializationObject.tangents) {
  85046. result.setTangents(serializationObject.tangents);
  85047. }
  85048. // Animations
  85049. if (serializationObject.animations) {
  85050. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85051. var parsedAnimation = serializationObject.animations[animationIndex];
  85052. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85053. }
  85054. }
  85055. return result;
  85056. };
  85057. /**
  85058. * Creates a MorphTarget from mesh data
  85059. * @param mesh defines the source mesh
  85060. * @param name defines the name to use for the new target
  85061. * @param influence defines the influence to attach to the target
  85062. * @returns a new MorphTarget
  85063. */
  85064. MorphTarget.FromMesh = function (mesh, name, influence) {
  85065. if (!name) {
  85066. name = mesh.name;
  85067. }
  85068. var result = new MorphTarget(name, influence);
  85069. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85071. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85072. }
  85073. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85074. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85075. }
  85076. return result;
  85077. };
  85078. return MorphTarget;
  85079. }());
  85080. BABYLON.MorphTarget = MorphTarget;
  85081. })(BABYLON || (BABYLON = {}));
  85082. //# sourceMappingURL=babylon.morphTarget.js.map
  85083. var BABYLON;
  85084. (function (BABYLON) {
  85085. /**
  85086. * This class is used to deform meshes using morphing between different targets
  85087. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85088. */
  85089. var MorphTargetManager = /** @class */ (function () {
  85090. /**
  85091. * Creates a new MorphTargetManager
  85092. * @param scene defines the current scene
  85093. */
  85094. function MorphTargetManager(scene) {
  85095. if (scene === void 0) { scene = null; }
  85096. this._targets = new Array();
  85097. this._targetObservable = new Array();
  85098. this._activeTargets = new BABYLON.SmartArray(16);
  85099. this._supportsNormals = false;
  85100. this._supportsTangents = false;
  85101. this._vertexCount = 0;
  85102. this._uniqueId = 0;
  85103. this._tempInfluences = new Array();
  85104. if (!scene) {
  85105. scene = BABYLON.Engine.LastCreatedScene;
  85106. }
  85107. this._scene = scene;
  85108. if (this._scene) {
  85109. this._scene.morphTargetManagers.push(this);
  85110. this._uniqueId = this._scene.getUniqueId();
  85111. }
  85112. }
  85113. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85114. /**
  85115. * Gets the unique ID of this manager
  85116. */
  85117. get: function () {
  85118. return this._uniqueId;
  85119. },
  85120. enumerable: true,
  85121. configurable: true
  85122. });
  85123. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85124. /**
  85125. * Gets the number of vertices handled by this manager
  85126. */
  85127. get: function () {
  85128. return this._vertexCount;
  85129. },
  85130. enumerable: true,
  85131. configurable: true
  85132. });
  85133. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85134. /**
  85135. * Gets a boolean indicating if this manager supports morphing of normals
  85136. */
  85137. get: function () {
  85138. return this._supportsNormals;
  85139. },
  85140. enumerable: true,
  85141. configurable: true
  85142. });
  85143. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85144. /**
  85145. * Gets a boolean indicating if this manager supports morphing of tangents
  85146. */
  85147. get: function () {
  85148. return this._supportsTangents;
  85149. },
  85150. enumerable: true,
  85151. configurable: true
  85152. });
  85153. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85154. /**
  85155. * Gets the number of targets stored in this manager
  85156. */
  85157. get: function () {
  85158. return this._targets.length;
  85159. },
  85160. enumerable: true,
  85161. configurable: true
  85162. });
  85163. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85164. /**
  85165. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85166. */
  85167. get: function () {
  85168. return this._activeTargets.length;
  85169. },
  85170. enumerable: true,
  85171. configurable: true
  85172. });
  85173. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85174. /**
  85175. * Gets the list of influences (one per target)
  85176. */
  85177. get: function () {
  85178. return this._influences;
  85179. },
  85180. enumerable: true,
  85181. configurable: true
  85182. });
  85183. /**
  85184. * Gets the active target at specified index. An active target is a target with an influence > 0
  85185. * @param index defines the index to check
  85186. * @returns the requested target
  85187. */
  85188. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85189. return this._activeTargets.data[index];
  85190. };
  85191. /**
  85192. * Gets the target at specified index
  85193. * @param index defines the index to check
  85194. * @returns the requested target
  85195. */
  85196. MorphTargetManager.prototype.getTarget = function (index) {
  85197. return this._targets[index];
  85198. };
  85199. /**
  85200. * Add a new target to this manager
  85201. * @param target defines the target to add
  85202. */
  85203. MorphTargetManager.prototype.addTarget = function (target) {
  85204. var _this = this;
  85205. this._targets.push(target);
  85206. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85207. _this._syncActiveTargets(needUpdate);
  85208. }));
  85209. this._syncActiveTargets(true);
  85210. };
  85211. /**
  85212. * Removes a target from the manager
  85213. * @param target defines the target to remove
  85214. */
  85215. MorphTargetManager.prototype.removeTarget = function (target) {
  85216. var index = this._targets.indexOf(target);
  85217. if (index >= 0) {
  85218. this._targets.splice(index, 1);
  85219. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85220. this._syncActiveTargets(true);
  85221. }
  85222. };
  85223. /**
  85224. * Serializes the current manager into a Serialization object
  85225. * @returns the serialized object
  85226. */
  85227. MorphTargetManager.prototype.serialize = function () {
  85228. var serializationObject = {};
  85229. serializationObject.id = this.uniqueId;
  85230. serializationObject.targets = [];
  85231. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85232. var target = _a[_i];
  85233. serializationObject.targets.push(target.serialize());
  85234. }
  85235. return serializationObject;
  85236. };
  85237. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85238. var influenceCount = 0;
  85239. this._activeTargets.reset();
  85240. this._supportsNormals = true;
  85241. this._supportsTangents = true;
  85242. this._vertexCount = 0;
  85243. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85244. var target = _a[_i];
  85245. this._activeTargets.push(target);
  85246. this._tempInfluences[influenceCount++] = target.influence;
  85247. var positions = target.getPositions();
  85248. if (positions) {
  85249. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85250. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85251. var vertexCount = positions.length / 3;
  85252. if (this._vertexCount === 0) {
  85253. this._vertexCount = vertexCount;
  85254. }
  85255. else if (this._vertexCount !== vertexCount) {
  85256. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85257. return;
  85258. }
  85259. }
  85260. }
  85261. if (!this._influences || this._influences.length !== influenceCount) {
  85262. this._influences = new Float32Array(influenceCount);
  85263. }
  85264. for (var index = 0; index < influenceCount; index++) {
  85265. this._influences[index] = this._tempInfluences[index];
  85266. }
  85267. if (needUpdate) {
  85268. this.synchronize();
  85269. }
  85270. };
  85271. /**
  85272. * Syncrhonize the targets with all the meshes using this morph target manager
  85273. */
  85274. MorphTargetManager.prototype.synchronize = function () {
  85275. if (!this._scene) {
  85276. return;
  85277. }
  85278. // Flag meshes as dirty to resync with the active targets
  85279. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85280. var mesh = _a[_i];
  85281. if (mesh.morphTargetManager === this) {
  85282. mesh._syncGeometryWithMorphTargetManager();
  85283. }
  85284. }
  85285. };
  85286. // Statics
  85287. /**
  85288. * Creates a new MorphTargetManager from serialized data
  85289. * @param serializationObject defines the serialized data
  85290. * @param scene defines the hosting scene
  85291. * @returns the new MorphTargetManager
  85292. */
  85293. MorphTargetManager.Parse = function (serializationObject, scene) {
  85294. var result = new MorphTargetManager(scene);
  85295. result._uniqueId = serializationObject.id;
  85296. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85297. var targetData = _a[_i];
  85298. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85299. }
  85300. return result;
  85301. };
  85302. return MorphTargetManager;
  85303. }());
  85304. BABYLON.MorphTargetManager = MorphTargetManager;
  85305. })(BABYLON || (BABYLON = {}));
  85306. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85307. var BABYLON;
  85308. (function (BABYLON) {
  85309. var Octree = /** @class */ (function () {
  85310. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85311. if (maxDepth === void 0) { maxDepth = 2; }
  85312. this.maxDepth = maxDepth;
  85313. this.dynamicContent = new Array();
  85314. this._maxBlockCapacity = maxBlockCapacity || 64;
  85315. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85316. this._creationFunc = creationFunc;
  85317. }
  85318. // Methods
  85319. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85320. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85321. };
  85322. Octree.prototype.addMesh = function (entry) {
  85323. for (var index = 0; index < this.blocks.length; index++) {
  85324. var block = this.blocks[index];
  85325. block.addEntry(entry);
  85326. }
  85327. };
  85328. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85329. this._selectionContent.reset();
  85330. for (var index = 0; index < this.blocks.length; index++) {
  85331. var block = this.blocks[index];
  85332. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85333. }
  85334. if (allowDuplicate) {
  85335. this._selectionContent.concat(this.dynamicContent);
  85336. }
  85337. else {
  85338. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85339. }
  85340. return this._selectionContent;
  85341. };
  85342. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85343. this._selectionContent.reset();
  85344. for (var index = 0; index < this.blocks.length; index++) {
  85345. var block = this.blocks[index];
  85346. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85347. }
  85348. if (allowDuplicate) {
  85349. this._selectionContent.concat(this.dynamicContent);
  85350. }
  85351. else {
  85352. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85353. }
  85354. return this._selectionContent;
  85355. };
  85356. Octree.prototype.intersectsRay = function (ray) {
  85357. this._selectionContent.reset();
  85358. for (var index = 0; index < this.blocks.length; index++) {
  85359. var block = this.blocks[index];
  85360. block.intersectsRay(ray, this._selectionContent);
  85361. }
  85362. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85363. return this._selectionContent;
  85364. };
  85365. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85366. target.blocks = new Array();
  85367. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85368. // Segmenting space
  85369. for (var x = 0; x < 2; x++) {
  85370. for (var y = 0; y < 2; y++) {
  85371. for (var z = 0; z < 2; z++) {
  85372. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85373. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85374. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85375. block.addEntries(entries);
  85376. target.blocks.push(block);
  85377. }
  85378. }
  85379. }
  85380. };
  85381. Octree.CreationFuncForMeshes = function (entry, block) {
  85382. var boundingInfo = entry.getBoundingInfo();
  85383. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85384. block.entries.push(entry);
  85385. }
  85386. };
  85387. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85388. var boundingInfo = entry.getBoundingInfo();
  85389. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85390. block.entries.push(entry);
  85391. }
  85392. };
  85393. return Octree;
  85394. }());
  85395. BABYLON.Octree = Octree;
  85396. })(BABYLON || (BABYLON = {}));
  85397. //# sourceMappingURL=babylon.octree.js.map
  85398. var BABYLON;
  85399. (function (BABYLON) {
  85400. var OctreeBlock = /** @class */ (function () {
  85401. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85402. this.entries = new Array();
  85403. this._boundingVectors = new Array();
  85404. this._capacity = capacity;
  85405. this._depth = depth;
  85406. this._maxDepth = maxDepth;
  85407. this._creationFunc = creationFunc;
  85408. this._minPoint = minPoint;
  85409. this._maxPoint = maxPoint;
  85410. this._boundingVectors.push(minPoint.clone());
  85411. this._boundingVectors.push(maxPoint.clone());
  85412. this._boundingVectors.push(minPoint.clone());
  85413. this._boundingVectors[2].x = maxPoint.x;
  85414. this._boundingVectors.push(minPoint.clone());
  85415. this._boundingVectors[3].y = maxPoint.y;
  85416. this._boundingVectors.push(minPoint.clone());
  85417. this._boundingVectors[4].z = maxPoint.z;
  85418. this._boundingVectors.push(maxPoint.clone());
  85419. this._boundingVectors[5].z = minPoint.z;
  85420. this._boundingVectors.push(maxPoint.clone());
  85421. this._boundingVectors[6].x = minPoint.x;
  85422. this._boundingVectors.push(maxPoint.clone());
  85423. this._boundingVectors[7].y = minPoint.y;
  85424. }
  85425. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85426. // Property
  85427. get: function () {
  85428. return this._capacity;
  85429. },
  85430. enumerable: true,
  85431. configurable: true
  85432. });
  85433. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85434. get: function () {
  85435. return this._minPoint;
  85436. },
  85437. enumerable: true,
  85438. configurable: true
  85439. });
  85440. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85441. get: function () {
  85442. return this._maxPoint;
  85443. },
  85444. enumerable: true,
  85445. configurable: true
  85446. });
  85447. // Methods
  85448. OctreeBlock.prototype.addEntry = function (entry) {
  85449. if (this.blocks) {
  85450. for (var index = 0; index < this.blocks.length; index++) {
  85451. var block = this.blocks[index];
  85452. block.addEntry(entry);
  85453. }
  85454. return;
  85455. }
  85456. this._creationFunc(entry, this);
  85457. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85458. this.createInnerBlocks();
  85459. }
  85460. };
  85461. OctreeBlock.prototype.addEntries = function (entries) {
  85462. for (var index = 0; index < entries.length; index++) {
  85463. var mesh = entries[index];
  85464. this.addEntry(mesh);
  85465. }
  85466. };
  85467. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85468. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85469. if (this.blocks) {
  85470. for (var index = 0; index < this.blocks.length; index++) {
  85471. var block = this.blocks[index];
  85472. block.select(frustumPlanes, selection, allowDuplicate);
  85473. }
  85474. return;
  85475. }
  85476. if (allowDuplicate) {
  85477. selection.concat(this.entries);
  85478. }
  85479. else {
  85480. selection.concatWithNoDuplicate(this.entries);
  85481. }
  85482. }
  85483. };
  85484. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85485. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85486. if (this.blocks) {
  85487. for (var index = 0; index < this.blocks.length; index++) {
  85488. var block = this.blocks[index];
  85489. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85490. }
  85491. return;
  85492. }
  85493. if (allowDuplicate) {
  85494. selection.concat(this.entries);
  85495. }
  85496. else {
  85497. selection.concatWithNoDuplicate(this.entries);
  85498. }
  85499. }
  85500. };
  85501. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85502. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85503. if (this.blocks) {
  85504. for (var index = 0; index < this.blocks.length; index++) {
  85505. var block = this.blocks[index];
  85506. block.intersectsRay(ray, selection);
  85507. }
  85508. return;
  85509. }
  85510. selection.concatWithNoDuplicate(this.entries);
  85511. }
  85512. };
  85513. OctreeBlock.prototype.createInnerBlocks = function () {
  85514. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85515. };
  85516. return OctreeBlock;
  85517. }());
  85518. BABYLON.OctreeBlock = OctreeBlock;
  85519. })(BABYLON || (BABYLON = {}));
  85520. //# sourceMappingURL=babylon.octreeBlock.js.map
  85521. var BABYLON;
  85522. (function (BABYLON) {
  85523. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  85524. __extends(VRDistortionCorrectionPostProcess, _super);
  85525. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  85526. var _this = _super.call(this, name, "vrDistortionCorrection", [
  85527. 'LensCenter',
  85528. 'Scale',
  85529. 'ScaleIn',
  85530. 'HmdWarpParam'
  85531. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  85532. _this._isRightEye = isRightEye;
  85533. _this._distortionFactors = vrMetrics.distortionK;
  85534. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  85535. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  85536. _this.adaptScaleToCurrentViewport = true;
  85537. _this.onSizeChangedObservable.add(function () {
  85538. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  85539. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  85540. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  85541. });
  85542. _this.onApplyObservable.add(function (effect) {
  85543. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  85544. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  85545. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  85546. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  85547. });
  85548. return _this;
  85549. }
  85550. return VRDistortionCorrectionPostProcess;
  85551. }(BABYLON.PostProcess));
  85552. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  85553. })(BABYLON || (BABYLON = {}));
  85554. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  85555. var BABYLON;
  85556. (function (BABYLON) {
  85557. var AnaglyphPostProcess = /** @class */ (function (_super) {
  85558. __extends(AnaglyphPostProcess, _super);
  85559. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  85560. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  85561. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85562. _this.onApplyObservable.add(function (effect) {
  85563. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  85564. });
  85565. return _this;
  85566. }
  85567. return AnaglyphPostProcess;
  85568. }(BABYLON.PostProcess));
  85569. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  85570. })(BABYLON || (BABYLON = {}));
  85571. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  85572. var BABYLON;
  85573. (function (BABYLON) {
  85574. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85575. __extends(StereoscopicInterlacePostProcess, _super);
  85576. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85577. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85578. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85579. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85580. _this.onSizeChangedObservable.add(function () {
  85581. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85582. });
  85583. _this.onApplyObservable.add(function (effect) {
  85584. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85585. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85586. });
  85587. return _this;
  85588. }
  85589. return StereoscopicInterlacePostProcess;
  85590. }(BABYLON.PostProcess));
  85591. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85592. })(BABYLON || (BABYLON = {}));
  85593. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85594. var BABYLON;
  85595. (function (BABYLON) {
  85596. /**
  85597. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85598. * Screen rotation is taken into account.
  85599. */
  85600. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85601. function FreeCameraDeviceOrientationInput() {
  85602. var _this = this;
  85603. this._screenOrientationAngle = 0;
  85604. this._screenQuaternion = new BABYLON.Quaternion();
  85605. this._alpha = 0;
  85606. this._beta = 0;
  85607. this._gamma = 0;
  85608. this._orientationChanged = function () {
  85609. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85610. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85611. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85612. };
  85613. this._deviceOrientation = function (evt) {
  85614. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85615. _this._beta = evt.beta !== null ? evt.beta : 0;
  85616. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85617. };
  85618. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85619. this._orientationChanged();
  85620. }
  85621. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85622. get: function () {
  85623. return this._camera;
  85624. },
  85625. set: function (camera) {
  85626. this._camera = camera;
  85627. if (this._camera != null && !this._camera.rotationQuaternion) {
  85628. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85629. }
  85630. },
  85631. enumerable: true,
  85632. configurable: true
  85633. });
  85634. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85635. window.addEventListener("orientationchange", this._orientationChanged);
  85636. window.addEventListener("deviceorientation", this._deviceOrientation);
  85637. //In certain cases, the attach control is called AFTER orientation was changed,
  85638. //So this is needed.
  85639. this._orientationChanged();
  85640. };
  85641. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85642. window.removeEventListener("orientationchange", this._orientationChanged);
  85643. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85644. };
  85645. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85646. //if no device orientation provided, don't update the rotation.
  85647. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85648. if (!this._alpha)
  85649. return;
  85650. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85651. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85652. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85653. //Mirror on XY Plane
  85654. this._camera.rotationQuaternion.z *= -1;
  85655. this._camera.rotationQuaternion.w *= -1;
  85656. };
  85657. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85658. return "FreeCameraDeviceOrientationInput";
  85659. };
  85660. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85661. return "deviceOrientation";
  85662. };
  85663. return FreeCameraDeviceOrientationInput;
  85664. }());
  85665. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85666. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85667. })(BABYLON || (BABYLON = {}));
  85668. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85669. var BABYLON;
  85670. (function (BABYLON) {
  85671. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85672. function ArcRotateCameraVRDeviceOrientationInput() {
  85673. this.alphaCorrection = 1;
  85674. this.betaCorrection = 1;
  85675. this.gammaCorrection = 1;
  85676. this._alpha = 0;
  85677. this._gamma = 0;
  85678. this._dirty = false;
  85679. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85680. }
  85681. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85682. this.camera.attachControl(element, noPreventDefault);
  85683. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85684. };
  85685. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85686. if (evt.alpha !== null) {
  85687. this._alpha = +evt.alpha | 0;
  85688. }
  85689. if (evt.gamma !== null) {
  85690. this._gamma = +evt.gamma | 0;
  85691. }
  85692. this._dirty = true;
  85693. };
  85694. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85695. if (this._dirty) {
  85696. this._dirty = false;
  85697. if (this._gamma < 0) {
  85698. this._gamma = 180 + this._gamma;
  85699. }
  85700. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85701. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85702. }
  85703. };
  85704. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85705. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85706. };
  85707. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85708. return "ArcRotateCameraVRDeviceOrientationInput";
  85709. };
  85710. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85711. return "VRDeviceOrientation";
  85712. };
  85713. return ArcRotateCameraVRDeviceOrientationInput;
  85714. }());
  85715. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85716. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85717. })(BABYLON || (BABYLON = {}));
  85718. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85719. var BABYLON;
  85720. (function (BABYLON) {
  85721. var VRCameraMetrics = /** @class */ (function () {
  85722. function VRCameraMetrics() {
  85723. this.compensateDistortion = true;
  85724. }
  85725. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85726. get: function () {
  85727. return this.hResolution / (2 * this.vResolution);
  85728. },
  85729. enumerable: true,
  85730. configurable: true
  85731. });
  85732. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85733. get: function () {
  85734. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85735. },
  85736. enumerable: true,
  85737. configurable: true
  85738. });
  85739. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85740. get: function () {
  85741. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85742. var h = (4 * meters) / this.hScreenSize;
  85743. return BABYLON.Matrix.Translation(h, 0, 0);
  85744. },
  85745. enumerable: true,
  85746. configurable: true
  85747. });
  85748. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85749. get: function () {
  85750. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85751. var h = (4 * meters) / this.hScreenSize;
  85752. return BABYLON.Matrix.Translation(-h, 0, 0);
  85753. },
  85754. enumerable: true,
  85755. configurable: true
  85756. });
  85757. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85758. get: function () {
  85759. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85760. },
  85761. enumerable: true,
  85762. configurable: true
  85763. });
  85764. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85765. get: function () {
  85766. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85767. },
  85768. enumerable: true,
  85769. configurable: true
  85770. });
  85771. VRCameraMetrics.GetDefault = function () {
  85772. var result = new VRCameraMetrics();
  85773. result.hResolution = 1280;
  85774. result.vResolution = 800;
  85775. result.hScreenSize = 0.149759993;
  85776. result.vScreenSize = 0.0935999975;
  85777. result.vScreenCenter = 0.0467999987;
  85778. result.eyeToScreenDistance = 0.0410000011;
  85779. result.lensSeparationDistance = 0.0635000020;
  85780. result.interpupillaryDistance = 0.0640000030;
  85781. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85782. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85783. result.postProcessScaleFactor = 1.714605507808412;
  85784. result.lensCenterOffset = 0.151976421;
  85785. return result;
  85786. };
  85787. return VRCameraMetrics;
  85788. }());
  85789. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85790. })(BABYLON || (BABYLON = {}));
  85791. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85792. var BABYLON;
  85793. (function (BABYLON) {
  85794. /**
  85795. * This represents a WebVR camera.
  85796. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85797. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85798. */
  85799. var WebVRFreeCamera = /** @class */ (function (_super) {
  85800. __extends(WebVRFreeCamera, _super);
  85801. /**
  85802. * Instantiates a WebVRFreeCamera.
  85803. * @param name The name of the WebVRFreeCamera
  85804. * @param position The starting anchor position for the camera
  85805. * @param scene The scene the camera belongs to
  85806. * @param webVROptions a set of customizable options for the webVRCamera
  85807. */
  85808. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85809. if (webVROptions === void 0) { webVROptions = {}; }
  85810. var _this = _super.call(this, name, position, scene) || this;
  85811. _this.webVROptions = webVROptions;
  85812. /**
  85813. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85814. */
  85815. _this._vrDevice = null;
  85816. /**
  85817. * The rawPose of the vrDevice.
  85818. */
  85819. _this.rawPose = null;
  85820. _this._specsVersion = "1.1";
  85821. _this._attached = false;
  85822. _this._descendants = [];
  85823. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85824. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85825. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85826. _this._standingMatrix = null;
  85827. /**
  85828. * Represents device position in babylon space.
  85829. */
  85830. _this.devicePosition = BABYLON.Vector3.Zero();
  85831. /**
  85832. * Represents device rotation in babylon space.
  85833. */
  85834. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85835. /**
  85836. * The scale of the device to be used when translating from device space to babylon space.
  85837. */
  85838. _this.deviceScaleFactor = 1;
  85839. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85840. _this._worldToDevice = BABYLON.Matrix.Identity();
  85841. /**
  85842. * References to the webVR controllers for the vrDevice.
  85843. */
  85844. _this.controllers = [];
  85845. /**
  85846. * Emits an event when a controller is attached.
  85847. */
  85848. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85849. /**
  85850. * Emits an event when a controller's mesh has been loaded;
  85851. */
  85852. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85853. /**
  85854. * If the rig cameras be used as parent instead of this camera.
  85855. */
  85856. _this.rigParenting = true;
  85857. _this._defaultHeight = undefined;
  85858. _this._workingVector = BABYLON.Vector3.Zero();
  85859. _this._oneVector = BABYLON.Vector3.One();
  85860. _this._workingMatrix = BABYLON.Matrix.Identity();
  85861. _this._cache.position = BABYLON.Vector3.Zero();
  85862. if (webVROptions.defaultHeight) {
  85863. _this._defaultHeight = webVROptions.defaultHeight;
  85864. _this.position.y = _this._defaultHeight;
  85865. }
  85866. _this.minZ = 0.1;
  85867. //legacy support - the compensation boolean was removed.
  85868. if (arguments.length === 5) {
  85869. _this.webVROptions = arguments[4];
  85870. }
  85871. // default webVR options
  85872. if (_this.webVROptions.trackPosition == undefined) {
  85873. _this.webVROptions.trackPosition = true;
  85874. }
  85875. if (_this.webVROptions.controllerMeshes == undefined) {
  85876. _this.webVROptions.controllerMeshes = true;
  85877. }
  85878. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85879. _this.webVROptions.defaultLightingOnControllers = true;
  85880. }
  85881. _this.rotationQuaternion = new BABYLON.Quaternion();
  85882. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85883. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85884. }
  85885. //enable VR
  85886. var engine = _this.getEngine();
  85887. _this._onVREnabled = function (success) { if (success) {
  85888. _this.initControllers();
  85889. } };
  85890. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85891. engine.initWebVR().add(function (event) {
  85892. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85893. return;
  85894. }
  85895. _this._vrDevice = event.vrDisplay;
  85896. //reset the rig parameters.
  85897. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85898. if (_this._attached) {
  85899. _this.getEngine().enableVR();
  85900. }
  85901. });
  85902. if (typeof (VRFrameData) !== "undefined")
  85903. _this._frameData = new VRFrameData();
  85904. /**
  85905. * The idea behind the following lines:
  85906. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85907. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85908. * the second will not show it correctly.
  85909. *
  85910. * To solve this - each object that has the camera as parent will be added to a protected array.
  85911. * When the rig camera renders, it will take this array and set all of those to be its children.
  85912. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85913. * Amazing!
  85914. */
  85915. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85916. if (camera.parent === _this && _this.rigParenting) {
  85917. _this._descendants = _this.getDescendants(true, function (n) {
  85918. // don't take the cameras or the controllers!
  85919. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85920. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85921. return !isController && !isRigCamera;
  85922. });
  85923. _this._descendants.forEach(function (node) {
  85924. node.parent = camera;
  85925. });
  85926. }
  85927. });
  85928. scene.onAfterCameraRenderObservable.add(function (camera) {
  85929. if (camera.parent === _this && _this.rigParenting) {
  85930. _this._descendants.forEach(function (node) {
  85931. node.parent = _this;
  85932. });
  85933. }
  85934. });
  85935. return _this;
  85936. }
  85937. /**
  85938. * Gets the device distance from the ground in meters.
  85939. * @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.
  85940. */
  85941. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85942. if (this._standingMatrix) {
  85943. // Add standing matrix offset to get real offset from ground in room
  85944. this._standingMatrix.getTranslationToRef(this._workingVector);
  85945. return this._deviceRoomPosition.y + this._workingVector.y;
  85946. }
  85947. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85948. return this._defaultHeight || 0;
  85949. };
  85950. /**
  85951. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85952. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85953. */
  85954. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85955. var _this = this;
  85956. if (callback === void 0) { callback = function (bool) { }; }
  85957. // Use standing matrix if available
  85958. this.getEngine().initWebVRAsync().then(function (result) {
  85959. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85960. callback(false);
  85961. }
  85962. else {
  85963. _this._standingMatrix = new BABYLON.Matrix();
  85964. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85965. if (!_this.getScene().useRightHandedSystem) {
  85966. [2, 6, 8, 9, 14].forEach(function (num) {
  85967. if (_this._standingMatrix) {
  85968. _this._standingMatrix.m[num] *= -1;
  85969. }
  85970. });
  85971. }
  85972. callback(true);
  85973. }
  85974. });
  85975. };
  85976. /**
  85977. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85978. * @returns A promise with a boolean set to if the standing matrix is supported.
  85979. */
  85980. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85981. var _this = this;
  85982. return new Promise(function (res, rej) {
  85983. _this.useStandingMatrix(function (supported) {
  85984. res(supported);
  85985. });
  85986. });
  85987. };
  85988. /**
  85989. * Disposes the camera
  85990. */
  85991. WebVRFreeCamera.prototype.dispose = function () {
  85992. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85993. _super.prototype.dispose.call(this);
  85994. };
  85995. /**
  85996. * Gets a vrController by name.
  85997. * @param name The name of the controller to retreive
  85998. * @returns the controller matching the name specified or null if not found
  85999. */
  86000. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86001. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86002. var gp = _a[_i];
  86003. if (gp.hand === name) {
  86004. return gp;
  86005. }
  86006. }
  86007. return null;
  86008. };
  86009. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86010. /**
  86011. * The controller corrisponding to the users left hand.
  86012. */
  86013. get: function () {
  86014. if (!this._leftController) {
  86015. this._leftController = this.getControllerByName("left");
  86016. }
  86017. return this._leftController;
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. ;
  86023. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86024. /**
  86025. * The controller corrisponding to the users right hand.
  86026. */
  86027. get: function () {
  86028. if (!this._rightController) {
  86029. this._rightController = this.getControllerByName("right");
  86030. }
  86031. return this._rightController;
  86032. },
  86033. enumerable: true,
  86034. configurable: true
  86035. });
  86036. ;
  86037. /**
  86038. * Casts a ray forward from the vrCamera's gaze.
  86039. * @param length Length of the ray (default: 100)
  86040. * @returns the ray corrisponding to the gaze
  86041. */
  86042. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86043. if (length === void 0) { length = 100; }
  86044. if (this.leftCamera) {
  86045. // Use left eye to avoid computation to compute center on every call
  86046. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86047. }
  86048. else {
  86049. return _super.prototype.getForwardRay.call(this, length);
  86050. }
  86051. };
  86052. /**
  86053. * Updates the camera based on device's frame data
  86054. */
  86055. WebVRFreeCamera.prototype._checkInputs = function () {
  86056. if (this._vrDevice && this._vrDevice.isPresenting) {
  86057. this._vrDevice.getFrameData(this._frameData);
  86058. this.updateFromDevice(this._frameData.pose);
  86059. }
  86060. _super.prototype._checkInputs.call(this);
  86061. };
  86062. /**
  86063. * Updates the poseControlled values based on the input device pose.
  86064. * @param poseData Pose coming from the device
  86065. */
  86066. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86067. if (poseData && poseData.orientation) {
  86068. this.rawPose = poseData;
  86069. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86070. if (this.getScene().useRightHandedSystem) {
  86071. this._deviceRoomRotationQuaternion.z *= -1;
  86072. this._deviceRoomRotationQuaternion.w *= -1;
  86073. }
  86074. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86075. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86076. if (this.getScene().useRightHandedSystem) {
  86077. this._deviceRoomPosition.z *= -1;
  86078. }
  86079. }
  86080. }
  86081. };
  86082. /**
  86083. * WebVR's attach control will start broadcasting frames to the device.
  86084. * Note that in certain browsers (chrome for example) this function must be called
  86085. * within a user-interaction callback. Example:
  86086. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86087. *
  86088. * @param element html element to attach the vrDevice to
  86089. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86090. */
  86091. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86092. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86093. this._attached = true;
  86094. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86095. if (this._vrDevice) {
  86096. this.getEngine().enableVR();
  86097. }
  86098. };
  86099. /**
  86100. * Detaches the camera from the html element and disables VR
  86101. *
  86102. * @param element html element to detach from
  86103. */
  86104. WebVRFreeCamera.prototype.detachControl = function (element) {
  86105. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86106. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86107. _super.prototype.detachControl.call(this, element);
  86108. this._attached = false;
  86109. this.getEngine().disableVR();
  86110. };
  86111. /**
  86112. * @returns the name of this class
  86113. */
  86114. WebVRFreeCamera.prototype.getClassName = function () {
  86115. return "WebVRFreeCamera";
  86116. };
  86117. /**
  86118. * Calls resetPose on the vrDisplay
  86119. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86120. */
  86121. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86122. //uses the vrDisplay's "resetPose()".
  86123. //pitch and roll won't be affected.
  86124. this._vrDevice.resetPose();
  86125. };
  86126. /**
  86127. * Updates the rig cameras (left and right eye)
  86128. */
  86129. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86130. var camLeft = this._rigCameras[0];
  86131. var camRight = this._rigCameras[1];
  86132. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86133. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86134. camLeft.position.copyFrom(this._deviceRoomPosition);
  86135. camRight.position.copyFrom(this._deviceRoomPosition);
  86136. };
  86137. /**
  86138. * Updates the cached values of the camera
  86139. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86140. */
  86141. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86142. var _this = this;
  86143. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86144. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86145. if (!this.updateCacheCalled) {
  86146. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86147. this.updateCacheCalled = true;
  86148. this.update();
  86149. }
  86150. // Set working vector to the device position in room space rotated by the new rotation
  86151. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86152. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86153. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86154. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86155. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86156. // Add translation from anchor position
  86157. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86158. this._workingVector.addInPlace(this.position);
  86159. this._workingVector.subtractInPlace(this._cache.position);
  86160. this._deviceToWorld.setTranslation(this._workingVector);
  86161. // Set an inverted matrix to be used when updating the camera
  86162. this._deviceToWorld.invertToRef(this._worldToDevice);
  86163. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86164. this.controllers.forEach(function (controller) {
  86165. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86166. controller.update();
  86167. });
  86168. }
  86169. if (!ignoreParentClass) {
  86170. _super.prototype._updateCache.call(this);
  86171. }
  86172. this.updateCacheCalled = false;
  86173. };
  86174. /**
  86175. * Updates the current device position and rotation in the babylon world
  86176. */
  86177. WebVRFreeCamera.prototype.update = function () {
  86178. // Get current device position in babylon world
  86179. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86180. // Get current device rotation in babylon world
  86181. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86182. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86183. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86184. _super.prototype.update.call(this);
  86185. };
  86186. /**
  86187. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86188. * @returns an identity matrix
  86189. */
  86190. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86191. return BABYLON.Matrix.Identity();
  86192. };
  86193. /**
  86194. * This function is called by the two RIG cameras.
  86195. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86196. */
  86197. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86198. var _this = this;
  86199. // Update the parent camera prior to using a child camera to avoid desynchronization
  86200. var parentCamera = this._cameraRigParams["parentCamera"];
  86201. parentCamera._updateCache();
  86202. //WebVR 1.1
  86203. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86204. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86205. if (!this.getScene().useRightHandedSystem) {
  86206. [2, 6, 8, 9, 14].forEach(function (num) {
  86207. _this._webvrViewMatrix.m[num] *= -1;
  86208. });
  86209. }
  86210. // update the camera rotation matrix
  86211. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86212. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86213. // Computing target and final matrix
  86214. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86215. // should the view matrix be updated with scale and position offset?
  86216. if (parentCamera.deviceScaleFactor !== 1) {
  86217. this._webvrViewMatrix.invert();
  86218. // scale the position, if set
  86219. if (parentCamera.deviceScaleFactor) {
  86220. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86221. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86222. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86223. }
  86224. this._webvrViewMatrix.invert();
  86225. }
  86226. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86227. return this._webvrViewMatrix;
  86228. };
  86229. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86230. var _this = this;
  86231. var parentCamera = this.parent;
  86232. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86233. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86234. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86235. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86236. //babylon compatible matrix
  86237. if (!this.getScene().useRightHandedSystem) {
  86238. [8, 9, 10, 11].forEach(function (num) {
  86239. _this._projectionMatrix.m[num] *= -1;
  86240. });
  86241. }
  86242. return this._projectionMatrix;
  86243. };
  86244. /**
  86245. * Initializes the controllers and their meshes
  86246. */
  86247. WebVRFreeCamera.prototype.initControllers = function () {
  86248. var _this = this;
  86249. this.controllers = [];
  86250. var manager = this.getScene().gamepadManager;
  86251. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86252. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86253. var webVrController = gamepad;
  86254. if (webVrController.defaultModel) {
  86255. webVrController.defaultModel.setEnabled(false);
  86256. }
  86257. if (webVrController.hand === "right") {
  86258. _this._rightController = null;
  86259. }
  86260. if (webVrController.hand === "left") {
  86261. _this._leftController = null;
  86262. }
  86263. var controllerIndex = _this.controllers.indexOf(webVrController);
  86264. if (controllerIndex !== -1) {
  86265. _this.controllers.splice(controllerIndex, 1);
  86266. }
  86267. }
  86268. });
  86269. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86270. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86271. var webVrController_1 = gamepad;
  86272. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86273. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86274. if (_this.webVROptions.controllerMeshes) {
  86275. if (webVrController_1.defaultModel) {
  86276. webVrController_1.defaultModel.setEnabled(true);
  86277. }
  86278. else {
  86279. // Load the meshes
  86280. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86281. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86282. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86283. if (_this.webVROptions.defaultLightingOnControllers) {
  86284. if (!_this._lightOnControllers) {
  86285. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86286. }
  86287. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86288. var children = mesh.getChildren();
  86289. if (children.length !== 0) {
  86290. children.forEach(function (mesh) {
  86291. light.includedOnlyMeshes.push(mesh);
  86292. activateLightOnSubMeshes_1(mesh, light);
  86293. });
  86294. }
  86295. };
  86296. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86297. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86298. }
  86299. });
  86300. }
  86301. }
  86302. webVrController_1.attachToPoseControlledCamera(_this);
  86303. // since this is async - sanity check. Is the controller already stored?
  86304. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86305. //add to the controllers array
  86306. _this.controllers.push(webVrController_1);
  86307. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86308. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86309. // So we're overriding setting left & right manually to be sure
  86310. var firstViveWandDetected = false;
  86311. for (var i = 0; i < _this.controllers.length; i++) {
  86312. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86313. if (!firstViveWandDetected) {
  86314. firstViveWandDetected = true;
  86315. _this.controllers[i].hand = "left";
  86316. }
  86317. else {
  86318. _this.controllers[i].hand = "right";
  86319. }
  86320. }
  86321. }
  86322. //did we find enough controllers? Great! let the developer know.
  86323. if (_this.controllers.length >= 2) {
  86324. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86325. }
  86326. }
  86327. }
  86328. });
  86329. };
  86330. return WebVRFreeCamera;
  86331. }(BABYLON.FreeCamera));
  86332. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86333. })(BABYLON || (BABYLON = {}));
  86334. //# sourceMappingURL=babylon.webVRCamera.js.map
  86335. var BABYLON;
  86336. (function (BABYLON) {
  86337. // We're mainly based on the logic defined into the FreeCamera code
  86338. /**
  86339. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86340. * being tilted forward or back and left or right.
  86341. */
  86342. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86343. __extends(DeviceOrientationCamera, _super);
  86344. /**
  86345. * Creates a new device orientation camera
  86346. * @param name The name of the camera
  86347. * @param position The start position camera
  86348. * @param scene The scene the camera belongs to
  86349. */
  86350. function DeviceOrientationCamera(name, position, scene) {
  86351. var _this = _super.call(this, name, position, scene) || this;
  86352. _this._quaternionCache = new BABYLON.Quaternion();
  86353. _this.inputs.addDeviceOrientation();
  86354. return _this;
  86355. }
  86356. /**
  86357. * Gets the current instance class name ("DeviceOrientationCamera").
  86358. * This helps avoiding instanceof at run time.
  86359. * @returns the class name
  86360. */
  86361. DeviceOrientationCamera.prototype.getClassName = function () {
  86362. return "DeviceOrientationCamera";
  86363. };
  86364. /**
  86365. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86366. */
  86367. DeviceOrientationCamera.prototype._checkInputs = function () {
  86368. _super.prototype._checkInputs.call(this);
  86369. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86370. if (this._initialQuaternion) {
  86371. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86372. }
  86373. };
  86374. /**
  86375. * Reset the camera to its default orientation on the specified axis only.
  86376. * @param axis The axis to reset
  86377. */
  86378. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86379. var _this = this;
  86380. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86381. //can only work if this camera has a rotation quaternion already.
  86382. if (!this.rotationQuaternion)
  86383. return;
  86384. if (!this._initialQuaternion) {
  86385. this._initialQuaternion = new BABYLON.Quaternion();
  86386. }
  86387. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86388. ['x', 'y', 'z'].forEach(function (axisName) {
  86389. if (!axis[axisName]) {
  86390. _this._initialQuaternion[axisName] = 0;
  86391. }
  86392. else {
  86393. _this._initialQuaternion[axisName] *= -1;
  86394. }
  86395. });
  86396. this._initialQuaternion.normalize();
  86397. //force rotation update
  86398. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86399. };
  86400. return DeviceOrientationCamera;
  86401. }(BABYLON.FreeCamera));
  86402. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86403. })(BABYLON || (BABYLON = {}));
  86404. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86405. var BABYLON;
  86406. (function (BABYLON) {
  86407. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86408. __extends(VRDeviceOrientationFreeCamera, _super);
  86409. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86410. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86411. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86412. var _this = _super.call(this, name, position, scene) || this;
  86413. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86414. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86415. return _this;
  86416. }
  86417. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86418. return "VRDeviceOrientationFreeCamera";
  86419. };
  86420. return VRDeviceOrientationFreeCamera;
  86421. }(BABYLON.DeviceOrientationCamera));
  86422. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86423. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86424. __extends(VRDeviceOrientationGamepadCamera, _super);
  86425. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86426. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86427. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86428. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86429. _this.inputs.addGamepad();
  86430. return _this;
  86431. }
  86432. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86433. return "VRDeviceOrientationGamepadCamera";
  86434. };
  86435. return VRDeviceOrientationGamepadCamera;
  86436. }(VRDeviceOrientationFreeCamera));
  86437. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86438. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86439. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86440. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86441. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86442. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86443. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86444. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86446. _this.inputs.addVRDeviceOrientation();
  86447. return _this;
  86448. }
  86449. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86450. return "VRDeviceOrientationArcRotateCamera";
  86451. };
  86452. return VRDeviceOrientationArcRotateCamera;
  86453. }(BABYLON.ArcRotateCamera));
  86454. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86455. })(BABYLON || (BABYLON = {}));
  86456. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86457. var BABYLON;
  86458. (function (BABYLON) {
  86459. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86460. __extends(AnaglyphFreeCamera, _super);
  86461. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86462. var _this = _super.call(this, name, position, scene) || this;
  86463. _this.interaxialDistance = interaxialDistance;
  86464. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86465. return _this;
  86466. }
  86467. AnaglyphFreeCamera.prototype.getClassName = function () {
  86468. return "AnaglyphFreeCamera";
  86469. };
  86470. return AnaglyphFreeCamera;
  86471. }(BABYLON.FreeCamera));
  86472. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86473. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86474. __extends(AnaglyphArcRotateCamera, _super);
  86475. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86476. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86477. _this.interaxialDistance = interaxialDistance;
  86478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86479. return _this;
  86480. }
  86481. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  86482. return "AnaglyphArcRotateCamera";
  86483. };
  86484. return AnaglyphArcRotateCamera;
  86485. }(BABYLON.ArcRotateCamera));
  86486. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  86487. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  86488. __extends(AnaglyphGamepadCamera, _super);
  86489. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  86490. var _this = _super.call(this, name, position, scene) || this;
  86491. _this.interaxialDistance = interaxialDistance;
  86492. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86493. return _this;
  86494. }
  86495. AnaglyphGamepadCamera.prototype.getClassName = function () {
  86496. return "AnaglyphGamepadCamera";
  86497. };
  86498. return AnaglyphGamepadCamera;
  86499. }(BABYLON.GamepadCamera));
  86500. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  86501. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  86502. __extends(AnaglyphUniversalCamera, _super);
  86503. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  86504. var _this = _super.call(this, name, position, scene) || this;
  86505. _this.interaxialDistance = interaxialDistance;
  86506. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86507. return _this;
  86508. }
  86509. AnaglyphUniversalCamera.prototype.getClassName = function () {
  86510. return "AnaglyphUniversalCamera";
  86511. };
  86512. return AnaglyphUniversalCamera;
  86513. }(BABYLON.UniversalCamera));
  86514. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  86515. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  86516. __extends(StereoscopicFreeCamera, _super);
  86517. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86518. var _this = _super.call(this, name, position, scene) || this;
  86519. _this.interaxialDistance = interaxialDistance;
  86520. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86521. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86522. return _this;
  86523. }
  86524. StereoscopicFreeCamera.prototype.getClassName = function () {
  86525. return "StereoscopicFreeCamera";
  86526. };
  86527. return StereoscopicFreeCamera;
  86528. }(BABYLON.FreeCamera));
  86529. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  86530. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  86531. __extends(StereoscopicArcRotateCamera, _super);
  86532. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  86533. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86534. _this.interaxialDistance = interaxialDistance;
  86535. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86536. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86537. return _this;
  86538. }
  86539. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  86540. return "StereoscopicArcRotateCamera";
  86541. };
  86542. return StereoscopicArcRotateCamera;
  86543. }(BABYLON.ArcRotateCamera));
  86544. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  86545. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  86546. __extends(StereoscopicGamepadCamera, _super);
  86547. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86548. var _this = _super.call(this, name, position, scene) || this;
  86549. _this.interaxialDistance = interaxialDistance;
  86550. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86551. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86552. return _this;
  86553. }
  86554. StereoscopicGamepadCamera.prototype.getClassName = function () {
  86555. return "StereoscopicGamepadCamera";
  86556. };
  86557. return StereoscopicGamepadCamera;
  86558. }(BABYLON.GamepadCamera));
  86559. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  86560. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  86561. __extends(StereoscopicUniversalCamera, _super);
  86562. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86563. var _this = _super.call(this, name, position, scene) || this;
  86564. _this.interaxialDistance = interaxialDistance;
  86565. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86566. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86567. return _this;
  86568. }
  86569. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86570. return "StereoscopicUniversalCamera";
  86571. };
  86572. return StereoscopicUniversalCamera;
  86573. }(BABYLON.UniversalCamera));
  86574. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86575. })(BABYLON || (BABYLON = {}));
  86576. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86577. var BABYLON;
  86578. (function (BABYLON) {
  86579. var VRExperienceHelperGazer = /** @class */ (function () {
  86580. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86581. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86582. this.scene = scene;
  86583. this._pointerDownOnMeshAsked = false;
  86584. this._isActionableMesh = false;
  86585. this._teleportationRequestInitiated = false;
  86586. this._teleportationBackRequestInitiated = false;
  86587. this._dpadPressed = true;
  86588. this._activePointer = false;
  86589. this._id = VRExperienceHelperGazer._idCounter++;
  86590. // Gaze tracker
  86591. if (!gazeTrackerToClone) {
  86592. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86593. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86594. this._gazeTracker.isPickable = false;
  86595. this._gazeTracker.isVisible = false;
  86596. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86597. targetMat.specularColor = BABYLON.Color3.Black();
  86598. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86599. targetMat.backFaceCulling = false;
  86600. this._gazeTracker.material = targetMat;
  86601. }
  86602. else {
  86603. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86604. }
  86605. }
  86606. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86607. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86608. };
  86609. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86610. this._pointerDownOnMeshAsked = true;
  86611. if (this._currentMeshSelected && this._currentHit) {
  86612. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86613. }
  86614. };
  86615. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86616. if (this._currentMeshSelected && this._currentHit) {
  86617. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86618. }
  86619. this._pointerDownOnMeshAsked = false;
  86620. };
  86621. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86622. this._activePointer = true;
  86623. };
  86624. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86625. this._activePointer = false;
  86626. };
  86627. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86628. };
  86629. VRExperienceHelperGazer.prototype.dispose = function () {
  86630. this._interactionsEnabled = false;
  86631. this._teleportationEnabled = false;
  86632. };
  86633. VRExperienceHelperGazer._idCounter = 0;
  86634. return VRExperienceHelperGazer;
  86635. }());
  86636. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86637. __extends(VRExperienceHelperControllerGazer, _super);
  86638. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86639. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86640. _this.webVRController = webVRController;
  86641. // Laser pointer
  86642. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86643. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86644. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86645. laserPointerMaterial.alpha = 0.6;
  86646. _this._laserPointer.material = laserPointerMaterial;
  86647. _this._laserPointer.rotation.x = Math.PI / 2;
  86648. _this._laserPointer.position.z = -0.5;
  86649. _this._laserPointer.isVisible = false;
  86650. if (!webVRController.mesh) {
  86651. // Create an empty mesh that is used prior to loading the high quality model
  86652. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86653. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86654. preloadPointerPose.rotation.x = -0.7;
  86655. preloadMesh.addChild(preloadPointerPose);
  86656. webVRController.attachToMesh(preloadMesh);
  86657. }
  86658. _this._setLaserPointerParent(webVRController.mesh);
  86659. return _this;
  86660. }
  86661. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86662. return this.webVRController.getForwardRay(length);
  86663. };
  86664. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86665. _super.prototype._activatePointer.call(this);
  86666. this._laserPointer.isVisible = true;
  86667. };
  86668. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86669. _super.prototype._deactivatePointer.call(this);
  86670. this._laserPointer.isVisible = false;
  86671. };
  86672. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86673. this._laserPointer.material.emissiveColor = color;
  86674. };
  86675. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86676. var makeNotPick = function (root) {
  86677. root.name += " laserPointer";
  86678. root.getChildMeshes().forEach(function (c) {
  86679. makeNotPick(c);
  86680. });
  86681. };
  86682. makeNotPick(mesh);
  86683. var childMeshes = mesh.getChildMeshes();
  86684. this.webVRController._pointingPoseNode = null;
  86685. for (var i = 0; i < childMeshes.length; i++) {
  86686. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86687. mesh = childMeshes[i];
  86688. this.webVRController._pointingPoseNode = mesh;
  86689. break;
  86690. }
  86691. }
  86692. this._laserPointer.parent = mesh;
  86693. };
  86694. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86695. this._laserPointer.scaling.y = distance;
  86696. this._laserPointer.position.z = -distance / 2;
  86697. };
  86698. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86699. _super.prototype.dispose.call(this);
  86700. this._laserPointer.dispose();
  86701. };
  86702. return VRExperienceHelperControllerGazer;
  86703. }(VRExperienceHelperGazer));
  86704. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86705. __extends(VRExperienceHelperCameraGazer, _super);
  86706. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86707. var _this = _super.call(this, scene) || this;
  86708. _this.getCamera = getCamera;
  86709. return _this;
  86710. }
  86711. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86712. var camera = this.getCamera();
  86713. if (camera) {
  86714. return camera.getForwardRay(length);
  86715. }
  86716. else {
  86717. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86718. }
  86719. };
  86720. return VRExperienceHelperCameraGazer;
  86721. }(VRExperienceHelperGazer));
  86722. /**
  86723. * Helps to quickly add VR support to an existing scene.
  86724. * See http://doc.babylonjs.com/how_to/webvr_helper
  86725. */
  86726. var VRExperienceHelper = /** @class */ (function () {
  86727. /**
  86728. * Instantiates a VRExperienceHelper.
  86729. * Helps to quickly add VR support to an existing scene.
  86730. * @param scene The scene the VRExperienceHelper belongs to.
  86731. * @param webVROptions Options to modify the vr experience helper's behavior.
  86732. */
  86733. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86734. if (webVROptions === void 0) { webVROptions = {}; }
  86735. var _this = this;
  86736. this.webVROptions = webVROptions;
  86737. // Can the system support WebVR, even if a headset isn't plugged in?
  86738. this._webVRsupported = false;
  86739. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86740. this._webVRready = false;
  86741. // Are we waiting for the requestPresent callback to complete?
  86742. this._webVRrequesting = false;
  86743. // Are we presenting to the headset right now?
  86744. this._webVRpresenting = false;
  86745. // Are we presenting in the fullscreen fallback?
  86746. this._fullscreenVRpresenting = false;
  86747. /**
  86748. * Observable raised when entering VR.
  86749. */
  86750. this.onEnteringVRObservable = new BABYLON.Observable();
  86751. /**
  86752. * Observable raised when exiting VR.
  86753. */
  86754. this.onExitingVRObservable = new BABYLON.Observable();
  86755. /**
  86756. * Observable raised when controller mesh is loaded.
  86757. */
  86758. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86759. this._useCustomVRButton = false;
  86760. this._teleportationRequested = false;
  86761. this._teleportActive = false;
  86762. this._floorMeshesCollection = [];
  86763. this._rotationAllowed = true;
  86764. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86765. this._rotationRightAsked = false;
  86766. this._rotationLeftAsked = false;
  86767. this._isDefaultTeleportationTarget = true;
  86768. this._teleportationFillColor = "#444444";
  86769. this._teleportationBorderColor = "#FFFFFF";
  86770. this._rotationAngle = 0;
  86771. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86772. this._padSensibilityUp = 0.65;
  86773. this._padSensibilityDown = 0.35;
  86774. this.leftController = null;
  86775. this.rightController = null;
  86776. /**
  86777. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86778. */
  86779. this.onNewMeshSelected = new BABYLON.Observable();
  86780. /**
  86781. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86782. */
  86783. this.onNewMeshPicked = new BABYLON.Observable();
  86784. /**
  86785. * Observable raised before camera teleportation
  86786. */
  86787. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86788. /**
  86789. * Observable raised after camera teleportation
  86790. */
  86791. this.onAfterCameraTeleport = new BABYLON.Observable();
  86792. /**
  86793. * Observable raised when current selected mesh gets unselected
  86794. */
  86795. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86796. /**
  86797. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86798. */
  86799. this.teleportationEnabled = true;
  86800. this._teleportationInitialized = false;
  86801. this._interactionsEnabled = false;
  86802. this._interactionsRequested = false;
  86803. this._displayGaze = true;
  86804. this._displayLaserPointer = true;
  86805. this._onResize = function () {
  86806. _this.moveButtonToBottomRight();
  86807. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86808. _this.exitVR();
  86809. }
  86810. };
  86811. this._onFullscreenChange = function () {
  86812. if (document.fullscreen !== undefined) {
  86813. _this._fullscreenVRpresenting = document.fullscreen;
  86814. }
  86815. else if (document.mozFullScreen !== undefined) {
  86816. _this._fullscreenVRpresenting = document.mozFullScreen;
  86817. }
  86818. else if (document.webkitIsFullScreen !== undefined) {
  86819. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86820. }
  86821. else if (document.msIsFullScreen !== undefined) {
  86822. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86823. }
  86824. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86825. _this.exitVR();
  86826. if (!_this._useCustomVRButton) {
  86827. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86828. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86829. }
  86830. }
  86831. };
  86832. this.beforeRender = function () {
  86833. if (_this.leftController && _this.leftController._activePointer) {
  86834. _this._castRayAndSelectObject(_this.leftController);
  86835. }
  86836. if (_this.rightController && _this.rightController._activePointer) {
  86837. _this._castRayAndSelectObject(_this.rightController);
  86838. }
  86839. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86840. _this._castRayAndSelectObject(_this._cameraGazer);
  86841. }
  86842. else {
  86843. _this._cameraGazer._gazeTracker.isVisible = false;
  86844. }
  86845. };
  86846. this._onNewGamepadConnected = function (gamepad) {
  86847. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86848. if (gamepad.leftStick) {
  86849. gamepad.onleftstickchanged(function (stickValues) {
  86850. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86851. // Listening to classic/xbox gamepad only if no VR controller is active
  86852. if ((!_this.leftController && !_this.rightController) ||
  86853. ((_this.leftController && !_this.leftController._activePointer) &&
  86854. (_this.rightController && !_this.rightController._activePointer))) {
  86855. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86856. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86857. }
  86858. }
  86859. });
  86860. }
  86861. if (gamepad.rightStick) {
  86862. gamepad.onrightstickchanged(function (stickValues) {
  86863. if (_this._teleportationInitialized) {
  86864. _this._checkRotate(stickValues, _this._cameraGazer);
  86865. }
  86866. });
  86867. }
  86868. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86869. gamepad.onbuttondown(function (buttonPressed) {
  86870. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86871. _this._cameraGazer._selectionPointerDown();
  86872. }
  86873. });
  86874. gamepad.onbuttonup(function (buttonPressed) {
  86875. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86876. _this._cameraGazer._selectionPointerUp();
  86877. }
  86878. });
  86879. }
  86880. }
  86881. else {
  86882. var webVRController = gamepad;
  86883. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86884. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86885. _this.rightController = controller;
  86886. }
  86887. else {
  86888. _this.leftController = controller;
  86889. }
  86890. _this._tryEnableInteractionOnController(controller);
  86891. }
  86892. };
  86893. // 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
  86894. this._tryEnableInteractionOnController = function (controller) {
  86895. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86896. _this._enableInteractionOnController(controller);
  86897. }
  86898. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86899. _this._enableTeleportationOnController(controller);
  86900. }
  86901. };
  86902. this._onNewGamepadDisconnected = function (gamepad) {
  86903. if (gamepad instanceof BABYLON.WebVRController) {
  86904. if (gamepad.hand === "left" && _this.leftController != null) {
  86905. _this.leftController.dispose();
  86906. _this.leftController = null;
  86907. }
  86908. if (gamepad.hand === "right" && _this.rightController != null) {
  86909. _this.rightController.dispose();
  86910. _this.rightController = null;
  86911. }
  86912. }
  86913. };
  86914. this._workingVector = BABYLON.Vector3.Zero();
  86915. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86916. this._workingMatrix = BABYLON.Matrix.Identity();
  86917. this._scene = scene;
  86918. this._canvas = scene.getEngine().getRenderingCanvas();
  86919. // Parse options
  86920. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86921. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86922. }
  86923. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86924. webVROptions.createDeviceOrientationCamera = true;
  86925. }
  86926. if (webVROptions.defaultHeight === undefined) {
  86927. webVROptions.defaultHeight = 1.7;
  86928. }
  86929. if (webVROptions.useCustomVRButton) {
  86930. this._useCustomVRButton = true;
  86931. if (webVROptions.customVRButton) {
  86932. this._btnVR = webVROptions.customVRButton;
  86933. }
  86934. }
  86935. if (webVROptions.rayLength) {
  86936. this._rayLength = webVROptions.rayLength;
  86937. }
  86938. this._defaultHeight = webVROptions.defaultHeight;
  86939. if (webVROptions.positionScale) {
  86940. this._rayLength *= webVROptions.positionScale;
  86941. this._defaultHeight *= webVROptions.positionScale;
  86942. }
  86943. // Set position
  86944. if (this._scene.activeCamera) {
  86945. this._position = this._scene.activeCamera.position.clone();
  86946. }
  86947. else {
  86948. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86949. }
  86950. // Set non-vr camera
  86951. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86952. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86953. // Copy data from existing camera
  86954. if (this._scene.activeCamera) {
  86955. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86956. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86957. // Set rotation from previous camera
  86958. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86959. var targetCamera = this._scene.activeCamera;
  86960. if (targetCamera.rotationQuaternion) {
  86961. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86962. }
  86963. else {
  86964. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86965. }
  86966. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86967. }
  86968. }
  86969. this._scene.activeCamera = this._deviceOrientationCamera;
  86970. if (this._canvas) {
  86971. this._scene.activeCamera.attachControl(this._canvas);
  86972. }
  86973. }
  86974. else {
  86975. this._existingCamera = this._scene.activeCamera;
  86976. }
  86977. // Create VR cameras
  86978. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86979. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86980. }
  86981. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86982. this._webVRCamera.useStandingMatrix();
  86983. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86984. // Create default button
  86985. if (!this._useCustomVRButton) {
  86986. this._btnVR = document.createElement("BUTTON");
  86987. this._btnVR.className = "babylonVRicon";
  86988. this._btnVR.id = "babylonVRiconbtn";
  86989. this._btnVR.title = "Click to switch to VR";
  86990. 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) }";
  86991. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86992. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86993. // css += ".babylonVRicon.vrdisplaysupported { }";
  86994. // css += ".babylonVRicon.vrdisplayready { }";
  86995. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86996. var style = document.createElement('style');
  86997. style.appendChild(document.createTextNode(css));
  86998. document.getElementsByTagName('head')[0].appendChild(style);
  86999. this.moveButtonToBottomRight();
  87000. }
  87001. // VR button click event
  87002. if (this._btnVR) {
  87003. this._btnVR.addEventListener("click", function () {
  87004. if (!_this.isInVRMode) {
  87005. _this.enterVR();
  87006. }
  87007. else {
  87008. _this.exitVR();
  87009. }
  87010. });
  87011. }
  87012. // Window events
  87013. window.addEventListener("resize", this._onResize);
  87014. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87015. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87016. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87017. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87018. // Display vr button when headset is connected
  87019. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87020. this.displayVRButton();
  87021. }
  87022. else {
  87023. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87024. if (e.vrDisplay) {
  87025. _this.displayVRButton();
  87026. }
  87027. });
  87028. }
  87029. // Exiting VR mode using 'ESC' key on desktop
  87030. this._onKeyDown = function (event) {
  87031. if (event.keyCode === 27 && _this.isInVRMode) {
  87032. _this.exitVR();
  87033. }
  87034. };
  87035. document.addEventListener("keydown", this._onKeyDown);
  87036. // Exiting VR mode double tapping the touch screen
  87037. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87038. if (_this.isInVRMode) {
  87039. _this.exitVR();
  87040. if (_this._fullscreenVRpresenting) {
  87041. _this._scene.getEngine().switchFullscreen(true);
  87042. }
  87043. }
  87044. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87045. // Listen for WebVR display changes
  87046. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87047. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87048. this._onVRRequestPresentStart = function () {
  87049. _this._webVRrequesting = true;
  87050. _this.updateButtonVisibility();
  87051. };
  87052. this._onVRRequestPresentComplete = function (success) {
  87053. _this._webVRrequesting = false;
  87054. _this.updateButtonVisibility();
  87055. };
  87056. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87057. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87058. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87059. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87060. scene.onDisposeObservable.add(function () {
  87061. _this.dispose();
  87062. });
  87063. // Gamepad connection events
  87064. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87065. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87066. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87067. this.updateButtonVisibility();
  87068. //create easing functions
  87069. this._circleEase = new BABYLON.CircleEase();
  87070. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87071. }
  87072. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87073. /** Return this.onEnteringVRObservable
  87074. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87075. */
  87076. get: function () {
  87077. return this.onEnteringVRObservable;
  87078. },
  87079. enumerable: true,
  87080. configurable: true
  87081. });
  87082. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87083. /** Return this.onExitingVRObservable
  87084. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87085. */
  87086. get: function () {
  87087. return this.onExitingVRObservable;
  87088. },
  87089. enumerable: true,
  87090. configurable: true
  87091. });
  87092. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87093. /** Return this.onControllerMeshLoadedObservable
  87094. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87095. */
  87096. get: function () {
  87097. return this.onControllerMeshLoadedObservable;
  87098. },
  87099. enumerable: true,
  87100. configurable: true
  87101. });
  87102. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87103. /**
  87104. * The mesh used to display where the user is going to teleport.
  87105. */
  87106. get: function () {
  87107. return this._teleportationTarget;
  87108. },
  87109. /**
  87110. * Sets the mesh to be used to display where the user is going to teleport.
  87111. */
  87112. set: function (value) {
  87113. if (value) {
  87114. value.name = "teleportationTarget";
  87115. this._isDefaultTeleportationTarget = false;
  87116. this._teleportationTarget = value;
  87117. }
  87118. },
  87119. enumerable: true,
  87120. configurable: true
  87121. });
  87122. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87123. /**
  87124. * The mesh used to display where the user is selecting,
  87125. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87126. * See http://doc.babylonjs.com/resources/baking_transformations
  87127. */
  87128. get: function () {
  87129. return this._cameraGazer._gazeTracker;
  87130. },
  87131. set: function (value) {
  87132. if (value) {
  87133. this._cameraGazer._gazeTracker = value;
  87134. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87135. this._cameraGazer._gazeTracker.isPickable = false;
  87136. this._cameraGazer._gazeTracker.isVisible = false;
  87137. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87138. if (this.leftController) {
  87139. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87140. }
  87141. if (this.rightController) {
  87142. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87143. }
  87144. }
  87145. },
  87146. enumerable: true,
  87147. configurable: true
  87148. });
  87149. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87150. /**
  87151. * If the ray of the gaze should be displayed.
  87152. */
  87153. get: function () {
  87154. return this._displayGaze;
  87155. },
  87156. /**
  87157. * Sets if the ray of the gaze should be displayed.
  87158. */
  87159. set: function (value) {
  87160. this._displayGaze = value;
  87161. if (!value) {
  87162. this._cameraGazer._gazeTracker.isVisible = false;
  87163. if (this.leftController) {
  87164. this.leftController._gazeTracker.isVisible = false;
  87165. }
  87166. if (this.rightController) {
  87167. this.rightController._gazeTracker.isVisible = false;
  87168. }
  87169. }
  87170. },
  87171. enumerable: true,
  87172. configurable: true
  87173. });
  87174. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87175. /**
  87176. * If the ray of the LaserPointer should be displayed.
  87177. */
  87178. get: function () {
  87179. return this._displayLaserPointer;
  87180. },
  87181. /**
  87182. * Sets if the ray of the LaserPointer should be displayed.
  87183. */
  87184. set: function (value) {
  87185. this._displayLaserPointer = value;
  87186. if (!value) {
  87187. if (this.rightController) {
  87188. this.rightController._deactivatePointer();
  87189. this.rightController._gazeTracker.isVisible = false;
  87190. }
  87191. if (this.leftController) {
  87192. this.leftController._deactivatePointer();
  87193. this.leftController._gazeTracker.isVisible = false;
  87194. }
  87195. }
  87196. else {
  87197. if (this.rightController) {
  87198. this.rightController._activatePointer();
  87199. }
  87200. else if (this.leftController) {
  87201. this.leftController._activatePointer();
  87202. }
  87203. }
  87204. },
  87205. enumerable: true,
  87206. configurable: true
  87207. });
  87208. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87209. /**
  87210. * The deviceOrientationCamera used as the camera when not in VR.
  87211. */
  87212. get: function () {
  87213. return this._deviceOrientationCamera;
  87214. },
  87215. enumerable: true,
  87216. configurable: true
  87217. });
  87218. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87219. /**
  87220. * Based on the current WebVR support, returns the current VR camera used.
  87221. */
  87222. get: function () {
  87223. if (this._webVRready) {
  87224. return this._webVRCamera;
  87225. }
  87226. else {
  87227. return this._scene.activeCamera;
  87228. }
  87229. },
  87230. enumerable: true,
  87231. configurable: true
  87232. });
  87233. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87234. /**
  87235. * The webVRCamera which is used when in VR.
  87236. */
  87237. get: function () {
  87238. return this._webVRCamera;
  87239. },
  87240. enumerable: true,
  87241. configurable: true
  87242. });
  87243. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87244. /**
  87245. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87246. */
  87247. get: function () {
  87248. return this._vrDeviceOrientationCamera;
  87249. },
  87250. enumerable: true,
  87251. configurable: true
  87252. });
  87253. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87254. get: function () {
  87255. var result = this._cameraGazer._teleportationRequestInitiated
  87256. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87257. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87258. return result;
  87259. },
  87260. enumerable: true,
  87261. configurable: true
  87262. });
  87263. // Raised when one of the controller has loaded successfully its associated default mesh
  87264. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87265. if (this.leftController && this.leftController.webVRController == webVRController) {
  87266. if (webVRController.mesh) {
  87267. this.leftController._setLaserPointerParent(webVRController.mesh);
  87268. }
  87269. }
  87270. if (this.rightController && this.rightController.webVRController == webVRController) {
  87271. if (webVRController.mesh) {
  87272. this.rightController._setLaserPointerParent(webVRController.mesh);
  87273. }
  87274. }
  87275. try {
  87276. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87277. }
  87278. catch (err) {
  87279. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87280. }
  87281. };
  87282. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87283. /**
  87284. * Gets a value indicating if we are currently in VR mode.
  87285. */
  87286. get: function () {
  87287. return this._webVRpresenting || this._fullscreenVRpresenting;
  87288. },
  87289. enumerable: true,
  87290. configurable: true
  87291. });
  87292. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87293. var vrDisplay = this._scene.getEngine().getVRDevice();
  87294. if (vrDisplay) {
  87295. var wasPresenting = this._webVRpresenting;
  87296. // A VR display is connected
  87297. this._webVRpresenting = vrDisplay.isPresenting;
  87298. if (wasPresenting && !this._webVRpresenting)
  87299. this.exitVR();
  87300. }
  87301. else {
  87302. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87303. }
  87304. this.updateButtonVisibility();
  87305. };
  87306. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87307. this._webVRsupported = eventArgs.vrSupported;
  87308. this._webVRready = !!eventArgs.vrDisplay;
  87309. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87310. this.updateButtonVisibility();
  87311. };
  87312. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87313. if (this._canvas && !this._useCustomVRButton) {
  87314. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87315. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87316. }
  87317. };
  87318. VRExperienceHelper.prototype.displayVRButton = function () {
  87319. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87320. document.body.appendChild(this._btnVR);
  87321. this._btnVRDisplayed = true;
  87322. }
  87323. };
  87324. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87325. if (!this._btnVR || this._useCustomVRButton) {
  87326. return;
  87327. }
  87328. this._btnVR.className = "babylonVRicon";
  87329. if (this.isInVRMode) {
  87330. this._btnVR.className += " vrdisplaypresenting";
  87331. }
  87332. else {
  87333. if (this._webVRready)
  87334. this._btnVR.className += " vrdisplayready";
  87335. if (this._webVRsupported)
  87336. this._btnVR.className += " vrdisplaysupported";
  87337. if (this._webVRrequesting)
  87338. this._btnVR.className += " vrdisplayrequesting";
  87339. }
  87340. };
  87341. /**
  87342. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87343. * Otherwise, will use the fullscreen API.
  87344. */
  87345. VRExperienceHelper.prototype.enterVR = function () {
  87346. if (this.onEnteringVRObservable) {
  87347. try {
  87348. this.onEnteringVRObservable.notifyObservers(this);
  87349. }
  87350. catch (err) {
  87351. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87352. }
  87353. }
  87354. if (this._scene.activeCamera) {
  87355. this._position = this._scene.activeCamera.position.clone();
  87356. // make sure that we return to the last active camera
  87357. this._existingCamera = this._scene.activeCamera;
  87358. }
  87359. if (this._webVRrequesting)
  87360. return;
  87361. // If WebVR is supported and a headset is connected
  87362. if (this._webVRready) {
  87363. if (!this._webVRpresenting) {
  87364. this._webVRCamera.position = this._position;
  87365. this._scene.activeCamera = this._webVRCamera;
  87366. }
  87367. }
  87368. else if (this._vrDeviceOrientationCamera) {
  87369. this._vrDeviceOrientationCamera.position = this._position;
  87370. if (this._scene.activeCamera) {
  87371. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87372. }
  87373. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87374. this._scene.getEngine().switchFullscreen(true);
  87375. this.updateButtonVisibility();
  87376. }
  87377. if (this._scene.activeCamera && this._canvas) {
  87378. this._scene.activeCamera.attachControl(this._canvas);
  87379. }
  87380. if (this._interactionsEnabled) {
  87381. this._scene.registerBeforeRender(this.beforeRender);
  87382. }
  87383. };
  87384. /**
  87385. * Attempt to exit VR, or fullscreen.
  87386. */
  87387. VRExperienceHelper.prototype.exitVR = function () {
  87388. if (this.onExitingVRObservable) {
  87389. try {
  87390. this.onExitingVRObservable.notifyObservers(this);
  87391. }
  87392. catch (err) {
  87393. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  87394. }
  87395. }
  87396. if (this._webVRpresenting) {
  87397. this._scene.getEngine().disableVR();
  87398. }
  87399. if (this._scene.activeCamera) {
  87400. this._position = this._scene.activeCamera.position.clone();
  87401. }
  87402. if (this._deviceOrientationCamera) {
  87403. this._deviceOrientationCamera.position = this._position;
  87404. this._scene.activeCamera = this._deviceOrientationCamera;
  87405. if (this._canvas) {
  87406. this._scene.activeCamera.attachControl(this._canvas);
  87407. }
  87408. }
  87409. else if (this._existingCamera) {
  87410. this._existingCamera.position = this._position;
  87411. this._scene.activeCamera = this._existingCamera;
  87412. }
  87413. this.updateButtonVisibility();
  87414. if (this._interactionsEnabled) {
  87415. this._scene.unregisterBeforeRender(this.beforeRender);
  87416. }
  87417. // resize to update width and height when exiting vr exits fullscreen
  87418. this._scene.getEngine().resize();
  87419. };
  87420. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  87421. /**
  87422. * The position of the vr experience helper.
  87423. */
  87424. get: function () {
  87425. return this._position;
  87426. },
  87427. /**
  87428. * Sets the position of the vr experience helper.
  87429. */
  87430. set: function (value) {
  87431. this._position = value;
  87432. if (this._scene.activeCamera) {
  87433. this._scene.activeCamera.position = value;
  87434. }
  87435. },
  87436. enumerable: true,
  87437. configurable: true
  87438. });
  87439. /**
  87440. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  87441. */
  87442. VRExperienceHelper.prototype.enableInteractions = function () {
  87443. var _this = this;
  87444. if (!this._interactionsEnabled) {
  87445. this._interactionsRequested = true;
  87446. if (this.leftController) {
  87447. this._enableInteractionOnController(this.leftController);
  87448. }
  87449. if (this.rightController) {
  87450. this._enableInteractionOnController(this.rightController);
  87451. }
  87452. this.raySelectionPredicate = function (mesh) {
  87453. return mesh.isVisible;
  87454. };
  87455. this.meshSelectionPredicate = function (mesh) {
  87456. return true;
  87457. };
  87458. this._raySelectionPredicate = function (mesh) {
  87459. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  87460. && mesh.name.indexOf("teleportationTarget") === -1
  87461. && mesh.name.indexOf("torusTeleportation") === -1
  87462. && mesh.name.indexOf("laserPointer") === -1)) {
  87463. return _this.raySelectionPredicate(mesh);
  87464. }
  87465. return false;
  87466. };
  87467. this._interactionsEnabled = true;
  87468. }
  87469. };
  87470. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  87471. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  87472. if (this._floorMeshesCollection[i].id === mesh.id) {
  87473. return true;
  87474. }
  87475. }
  87476. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  87477. return true;
  87478. }
  87479. return false;
  87480. };
  87481. /**
  87482. * Adds a floor mesh to be used for teleportation.
  87483. * @param floorMesh the mesh to be used for teleportation.
  87484. */
  87485. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  87486. if (!this._floorMeshesCollection) {
  87487. return;
  87488. }
  87489. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  87490. return;
  87491. }
  87492. this._floorMeshesCollection.push(floorMesh);
  87493. };
  87494. /**
  87495. * Removes a floor mesh from being used for teleportation.
  87496. * @param floorMesh the mesh to be removed.
  87497. */
  87498. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  87499. if (!this._floorMeshesCollection) {
  87500. return;
  87501. }
  87502. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  87503. if (meshIndex !== -1) {
  87504. this._floorMeshesCollection.splice(meshIndex, 1);
  87505. }
  87506. };
  87507. /**
  87508. * Enables interactions and teleportation using the VR controllers and gaze.
  87509. * @param vrTeleportationOptions options to modify teleportation behavior.
  87510. */
  87511. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  87512. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  87513. if (!this._teleportationInitialized) {
  87514. this._teleportationRequested = true;
  87515. this.enableInteractions();
  87516. if (vrTeleportationOptions.floorMeshName) {
  87517. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  87518. }
  87519. if (vrTeleportationOptions.floorMeshes) {
  87520. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  87521. }
  87522. if (this.leftController != null) {
  87523. this._enableTeleportationOnController(this.leftController);
  87524. }
  87525. if (this.rightController != null) {
  87526. this._enableTeleportationOnController(this.rightController);
  87527. }
  87528. // Creates an image processing post process for the vignette not relying
  87529. // on the main scene configuration for image processing to reduce setup and spaces
  87530. // (gamma/linear) conflicts.
  87531. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  87532. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87533. imageProcessingConfiguration.vignetteEnabled = true;
  87534. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  87535. this._webVRCamera.detachPostProcess(this._postProcessMove);
  87536. this._teleportationInitialized = true;
  87537. if (this._isDefaultTeleportationTarget) {
  87538. this._createTeleportationCircles();
  87539. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  87540. }
  87541. }
  87542. };
  87543. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  87544. var _this = this;
  87545. var controllerMesh = controller.webVRController.mesh;
  87546. if (controllerMesh) {
  87547. controller._interactionsEnabled = true;
  87548. controller._activatePointer();
  87549. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  87550. // Enabling / disabling laserPointer
  87551. if (_this._displayLaserPointer && stateObject.value === 1) {
  87552. if (controller._activePointer) {
  87553. controller._deactivatePointer();
  87554. }
  87555. else {
  87556. controller._activatePointer();
  87557. }
  87558. if (_this.displayGaze) {
  87559. controller._gazeTracker.isVisible = controller._activePointer;
  87560. }
  87561. }
  87562. });
  87563. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  87564. if (!controller._pointerDownOnMeshAsked) {
  87565. if (stateObject.value > _this._padSensibilityUp) {
  87566. controller._selectionPointerDown();
  87567. }
  87568. }
  87569. else if (stateObject.value < _this._padSensibilityDown) {
  87570. controller._selectionPointerUp();
  87571. }
  87572. });
  87573. }
  87574. };
  87575. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87576. // Dont teleport if another gaze already requested teleportation
  87577. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87578. return;
  87579. }
  87580. if (!gazer._teleportationRequestInitiated) {
  87581. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87582. gazer._activatePointer();
  87583. gazer._teleportationRequestInitiated = true;
  87584. }
  87585. }
  87586. else {
  87587. // Listening to the proper controller values changes to confirm teleportation
  87588. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87589. if (this._teleportActive) {
  87590. this._teleportCamera(this._haloCenter);
  87591. }
  87592. gazer._teleportationRequestInitiated = false;
  87593. }
  87594. }
  87595. };
  87596. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87597. // Only rotate when user is not currently selecting a teleportation location
  87598. if (gazer._teleportationRequestInitiated) {
  87599. return;
  87600. }
  87601. if (!this._rotationLeftAsked) {
  87602. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87603. this._rotationLeftAsked = true;
  87604. if (this._rotationAllowed) {
  87605. this._rotateCamera(false);
  87606. }
  87607. }
  87608. }
  87609. else {
  87610. if (stateObject.x > -this._padSensibilityDown) {
  87611. this._rotationLeftAsked = false;
  87612. }
  87613. }
  87614. if (!this._rotationRightAsked) {
  87615. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87616. this._rotationRightAsked = true;
  87617. if (this._rotationAllowed) {
  87618. this._rotateCamera(true);
  87619. }
  87620. }
  87621. }
  87622. else {
  87623. if (stateObject.x < this._padSensibilityDown) {
  87624. this._rotationRightAsked = false;
  87625. }
  87626. }
  87627. };
  87628. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87629. // Only teleport backwards when user is not currently selecting a teleportation location
  87630. if (gazer._teleportationRequestInitiated) {
  87631. return;
  87632. }
  87633. // Teleport backwards
  87634. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87635. if (!gazer._teleportationBackRequestInitiated) {
  87636. if (!this.currentVRCamera) {
  87637. return;
  87638. }
  87639. // Get rotation and position of the current camera
  87640. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87641. var position = this.currentVRCamera.position;
  87642. // If the camera has device position, use that instead
  87643. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87644. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87645. position = this.currentVRCamera.devicePosition;
  87646. }
  87647. // Get matrix with only the y rotation of the device rotation
  87648. rotation.toEulerAnglesToRef(this._workingVector);
  87649. this._workingVector.z = 0;
  87650. this._workingVector.x = 0;
  87651. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87652. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87653. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87654. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87655. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87656. var ray = new BABYLON.Ray(position, this._workingVector);
  87657. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87658. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87659. this._teleportCamera(hit.pickedPoint);
  87660. }
  87661. gazer._teleportationBackRequestInitiated = true;
  87662. }
  87663. }
  87664. else {
  87665. gazer._teleportationBackRequestInitiated = false;
  87666. }
  87667. };
  87668. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87669. var _this = this;
  87670. var controllerMesh = controller.webVRController.mesh;
  87671. if (controllerMesh) {
  87672. if (!controller._interactionsEnabled) {
  87673. this._enableInteractionOnController(controller);
  87674. }
  87675. controller._interactionsEnabled = true;
  87676. controller._teleportationEnabled = true;
  87677. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87678. controller._dpadPressed = false;
  87679. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87680. controller._dpadPressed = stateObject.pressed;
  87681. if (!controller._dpadPressed) {
  87682. _this._rotationLeftAsked = false;
  87683. _this._rotationRightAsked = false;
  87684. controller._teleportationBackRequestInitiated = false;
  87685. }
  87686. });
  87687. }
  87688. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87689. if (_this.teleportationEnabled) {
  87690. _this._checkTeleportBackwards(stateObject, controller);
  87691. _this._checkTeleportWithRay(stateObject, controller);
  87692. }
  87693. _this._checkRotate(stateObject, controller);
  87694. });
  87695. }
  87696. };
  87697. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87698. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87699. this._teleportationTarget.isPickable = false;
  87700. var length = 512;
  87701. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87702. dynamicTexture.hasAlpha = true;
  87703. var context = dynamicTexture.getContext();
  87704. var centerX = length / 2;
  87705. var centerY = length / 2;
  87706. var radius = 200;
  87707. context.beginPath();
  87708. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87709. context.fillStyle = this._teleportationFillColor;
  87710. context.fill();
  87711. context.lineWidth = 10;
  87712. context.strokeStyle = this._teleportationBorderColor;
  87713. context.stroke();
  87714. context.closePath();
  87715. dynamicTexture.update();
  87716. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87717. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87718. this._teleportationTarget.material = teleportationCircleMaterial;
  87719. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87720. torus.isPickable = false;
  87721. torus.parent = this._teleportationTarget;
  87722. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87723. var keys = [];
  87724. keys.push({
  87725. frame: 0,
  87726. value: 0
  87727. });
  87728. keys.push({
  87729. frame: 30,
  87730. value: 0.4
  87731. });
  87732. keys.push({
  87733. frame: 60,
  87734. value: 0
  87735. });
  87736. animationInnerCircle.setKeys(keys);
  87737. var easingFunction = new BABYLON.SineEase();
  87738. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87739. animationInnerCircle.setEasingFunction(easingFunction);
  87740. torus.animations = [];
  87741. torus.animations.push(animationInnerCircle);
  87742. this._scene.beginAnimation(torus, 0, 60, true);
  87743. this._hideTeleportationTarget();
  87744. };
  87745. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87746. this._teleportActive = true;
  87747. if (this._teleportationInitialized) {
  87748. this._teleportationTarget.isVisible = true;
  87749. if (this._isDefaultTeleportationTarget) {
  87750. this._teleportationTarget.getChildren()[0].isVisible = true;
  87751. }
  87752. }
  87753. };
  87754. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87755. this._teleportActive = false;
  87756. if (this._teleportationInitialized) {
  87757. this._teleportationTarget.isVisible = false;
  87758. if (this._isDefaultTeleportationTarget) {
  87759. this._teleportationTarget.getChildren()[0].isVisible = false;
  87760. }
  87761. }
  87762. };
  87763. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87764. var _this = this;
  87765. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87766. return;
  87767. }
  87768. if (right) {
  87769. this._rotationAngle++;
  87770. }
  87771. else {
  87772. this._rotationAngle--;
  87773. }
  87774. this.currentVRCamera.animations = [];
  87775. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87776. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87777. var animationRotationKeys = [];
  87778. animationRotationKeys.push({
  87779. frame: 0,
  87780. value: this.currentVRCamera.rotationQuaternion
  87781. });
  87782. animationRotationKeys.push({
  87783. frame: 6,
  87784. value: target
  87785. });
  87786. animationRotation.setKeys(animationRotationKeys);
  87787. animationRotation.setEasingFunction(this._circleEase);
  87788. this.currentVRCamera.animations.push(animationRotation);
  87789. this._postProcessMove.animations = [];
  87790. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87791. var vignetteWeightKeys = [];
  87792. vignetteWeightKeys.push({
  87793. frame: 0,
  87794. value: 0
  87795. });
  87796. vignetteWeightKeys.push({
  87797. frame: 3,
  87798. value: 4
  87799. });
  87800. vignetteWeightKeys.push({
  87801. frame: 6,
  87802. value: 0
  87803. });
  87804. animationPP.setKeys(vignetteWeightKeys);
  87805. animationPP.setEasingFunction(this._circleEase);
  87806. this._postProcessMove.animations.push(animationPP);
  87807. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87808. var vignetteStretchKeys = [];
  87809. vignetteStretchKeys.push({
  87810. frame: 0,
  87811. value: 0
  87812. });
  87813. vignetteStretchKeys.push({
  87814. frame: 3,
  87815. value: 10
  87816. });
  87817. vignetteStretchKeys.push({
  87818. frame: 6,
  87819. value: 0
  87820. });
  87821. animationPP2.setKeys(vignetteStretchKeys);
  87822. animationPP2.setEasingFunction(this._circleEase);
  87823. this._postProcessMove.animations.push(animationPP2);
  87824. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87825. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87826. this._postProcessMove.samples = 4;
  87827. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87828. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87829. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87830. });
  87831. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87832. };
  87833. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87834. if (hit.pickedPoint) {
  87835. if (gazer._teleportationRequestInitiated) {
  87836. this._displayTeleportationTarget();
  87837. this._haloCenter.copyFrom(hit.pickedPoint);
  87838. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87839. }
  87840. var pickNormal = hit.getNormal(true, false);
  87841. if (pickNormal) {
  87842. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87843. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87844. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87845. }
  87846. this._teleportationTarget.position.y += 0.1;
  87847. }
  87848. };
  87849. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87850. var _this = this;
  87851. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87852. return;
  87853. }
  87854. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87855. // offset of the headset from the anchor.
  87856. if (this.webVRCamera.leftCamera) {
  87857. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87858. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87859. location.subtractToRef(this._workingVector, this._workingVector);
  87860. }
  87861. else {
  87862. this._workingVector.copyFrom(location);
  87863. }
  87864. // Add height to account for user's height offset
  87865. if (this.isInVRMode) {
  87866. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87867. }
  87868. else {
  87869. this._workingVector.y += this._defaultHeight;
  87870. }
  87871. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87872. // Create animation from the camera's position to the new location
  87873. this.currentVRCamera.animations = [];
  87874. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87875. var animationCameraTeleportationKeys = [{
  87876. frame: 0,
  87877. value: this.currentVRCamera.position
  87878. },
  87879. {
  87880. frame: 11,
  87881. value: this._workingVector
  87882. }
  87883. ];
  87884. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87885. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87886. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87887. this._postProcessMove.animations = [];
  87888. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87889. var vignetteWeightKeys = [];
  87890. vignetteWeightKeys.push({
  87891. frame: 0,
  87892. value: 0
  87893. });
  87894. vignetteWeightKeys.push({
  87895. frame: 5,
  87896. value: 8
  87897. });
  87898. vignetteWeightKeys.push({
  87899. frame: 11,
  87900. value: 0
  87901. });
  87902. animationPP.setKeys(vignetteWeightKeys);
  87903. this._postProcessMove.animations.push(animationPP);
  87904. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87905. var vignetteStretchKeys = [];
  87906. vignetteStretchKeys.push({
  87907. frame: 0,
  87908. value: 0
  87909. });
  87910. vignetteStretchKeys.push({
  87911. frame: 5,
  87912. value: 10
  87913. });
  87914. vignetteStretchKeys.push({
  87915. frame: 11,
  87916. value: 0
  87917. });
  87918. animationPP2.setKeys(vignetteStretchKeys);
  87919. this._postProcessMove.animations.push(animationPP2);
  87920. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87921. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87922. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87923. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87924. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87925. });
  87926. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87927. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87928. });
  87929. this._hideTeleportationTarget();
  87930. };
  87931. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87932. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87933. return;
  87934. }
  87935. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87936. // Moving the gazeTracker on the mesh face targetted
  87937. if (hit && hit.pickedPoint) {
  87938. if (this._displayGaze) {
  87939. var multiplier = 1;
  87940. gazer._gazeTracker.isVisible = true;
  87941. if (gazer._isActionableMesh) {
  87942. multiplier = 3;
  87943. }
  87944. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87945. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87946. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87947. var pickNormal = hit.getNormal();
  87948. // To avoid z-fighting
  87949. var deltaFighting = 0.002;
  87950. if (pickNormal) {
  87951. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87952. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87953. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87954. }
  87955. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87956. if (gazer._gazeTracker.position.x < 0) {
  87957. gazer._gazeTracker.position.x += deltaFighting;
  87958. }
  87959. else {
  87960. gazer._gazeTracker.position.x -= deltaFighting;
  87961. }
  87962. if (gazer._gazeTracker.position.y < 0) {
  87963. gazer._gazeTracker.position.y += deltaFighting;
  87964. }
  87965. else {
  87966. gazer._gazeTracker.position.y -= deltaFighting;
  87967. }
  87968. if (gazer._gazeTracker.position.z < 0) {
  87969. gazer._gazeTracker.position.z += deltaFighting;
  87970. }
  87971. else {
  87972. gazer._gazeTracker.position.z -= deltaFighting;
  87973. }
  87974. }
  87975. // Changing the size of the laser pointer based on the distance from the targetted point
  87976. gazer._updatePointerDistance(hit.distance);
  87977. }
  87978. else {
  87979. gazer._gazeTracker.isVisible = false;
  87980. }
  87981. if (hit && hit.pickedMesh) {
  87982. gazer._currentHit = hit;
  87983. if (gazer._pointerDownOnMeshAsked) {
  87984. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87985. }
  87986. // The object selected is the floor, we're in a teleportation scenario
  87987. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87988. // Moving the teleportation area to this targetted point
  87989. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87990. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87991. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87992. }
  87993. gazer._currentMeshSelected = null;
  87994. if (gazer._teleportationRequestInitiated) {
  87995. this._moveTeleportationSelectorTo(hit, gazer);
  87996. }
  87997. return;
  87998. }
  87999. // If not, we're in a selection scenario
  88000. //this._teleportationAllowed = false;
  88001. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88002. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88003. this.onNewMeshPicked.notifyObservers(hit);
  88004. gazer._currentMeshSelected = hit.pickedMesh;
  88005. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88006. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88007. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88008. gazer._isActionableMesh = true;
  88009. }
  88010. else {
  88011. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88012. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88013. gazer._isActionableMesh = false;
  88014. }
  88015. try {
  88016. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88017. }
  88018. catch (err) {
  88019. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88020. }
  88021. }
  88022. else {
  88023. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88024. gazer._currentMeshSelected = null;
  88025. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88026. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88027. }
  88028. }
  88029. }
  88030. else {
  88031. gazer._currentHit = null;
  88032. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88033. gazer._currentMeshSelected = null;
  88034. //this._teleportationAllowed = false;
  88035. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88036. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88037. }
  88038. };
  88039. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88040. if (mesh) {
  88041. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88042. }
  88043. };
  88044. /**
  88045. * Sets the color of the laser ray from the vr controllers.
  88046. * @param color new color for the ray.
  88047. */
  88048. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88049. if (this.leftController) {
  88050. this.leftController._setLaserPointerColor(color);
  88051. }
  88052. if (this.rightController) {
  88053. this.rightController._setLaserPointerColor(color);
  88054. }
  88055. };
  88056. /**
  88057. * Sets the color of the ray from the vr headsets gaze.
  88058. * @param color new color for the ray.
  88059. */
  88060. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88061. if (!this._cameraGazer._gazeTracker.material) {
  88062. return;
  88063. }
  88064. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88065. if (this.leftController) {
  88066. this.leftController._gazeTracker.material.emissiveColor = color;
  88067. }
  88068. if (this.rightController) {
  88069. this.rightController._gazeTracker.material.emissiveColor = color;
  88070. }
  88071. };
  88072. /**
  88073. * Exits VR and disposes of the vr experience helper
  88074. */
  88075. VRExperienceHelper.prototype.dispose = function () {
  88076. if (this.isInVRMode) {
  88077. this.exitVR();
  88078. }
  88079. if (this._postProcessMove) {
  88080. this._postProcessMove.dispose();
  88081. }
  88082. if (this._webVRCamera) {
  88083. this._webVRCamera.dispose();
  88084. }
  88085. if (this._vrDeviceOrientationCamera) {
  88086. this._vrDeviceOrientationCamera.dispose();
  88087. }
  88088. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88089. document.body.removeChild(this._btnVR);
  88090. }
  88091. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88092. this._deviceOrientationCamera.dispose();
  88093. }
  88094. if (this._cameraGazer) {
  88095. this._cameraGazer.dispose();
  88096. }
  88097. if (this.leftController) {
  88098. this.leftController.dispose();
  88099. }
  88100. if (this.rightController) {
  88101. this.rightController.dispose();
  88102. }
  88103. if (this._teleportationTarget) {
  88104. this._teleportationTarget.dispose();
  88105. }
  88106. this._floorMeshesCollection = [];
  88107. document.removeEventListener("keydown", this._onKeyDown);
  88108. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88109. window.removeEventListener("resize", this._onResize);
  88110. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88111. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88112. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88113. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88114. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88115. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88116. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88117. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88118. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88119. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88120. this._scene.unregisterBeforeRender(this.beforeRender);
  88121. };
  88122. /**
  88123. * Gets the name of the VRExperienceHelper class
  88124. * @returns "VRExperienceHelper"
  88125. */
  88126. VRExperienceHelper.prototype.getClassName = function () {
  88127. return "VRExperienceHelper";
  88128. };
  88129. return VRExperienceHelper;
  88130. }());
  88131. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88132. })(BABYLON || (BABYLON = {}));
  88133. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88134. // Mainly based on these 2 articles :
  88135. // 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
  88136. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88137. var BABYLON;
  88138. (function (BABYLON) {
  88139. /**
  88140. * Defines the potential axis of a Joystick
  88141. */
  88142. var JoystickAxis;
  88143. (function (JoystickAxis) {
  88144. /** X axis */
  88145. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88146. /** Y axis */
  88147. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88148. /** Z axis */
  88149. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88150. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88151. /**
  88152. * Class used to define virtual joystick (used in touch mode)
  88153. */
  88154. var VirtualJoystick = /** @class */ (function () {
  88155. /**
  88156. * Creates a new virtual joystick
  88157. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88158. */
  88159. function VirtualJoystick(leftJoystick) {
  88160. var _this = this;
  88161. if (leftJoystick) {
  88162. this._leftJoystick = true;
  88163. }
  88164. else {
  88165. this._leftJoystick = false;
  88166. }
  88167. VirtualJoystick._globalJoystickIndex++;
  88168. // By default left & right arrow keys are moving the X
  88169. // and up & down keys are moving the Y
  88170. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88171. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88172. this.reverseLeftRight = false;
  88173. this.reverseUpDown = false;
  88174. // collections of pointers
  88175. this._touches = new BABYLON.StringDictionary();
  88176. this.deltaPosition = BABYLON.Vector3.Zero();
  88177. this._joystickSensibility = 25;
  88178. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88179. this._onResize = function (evt) {
  88180. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88181. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88182. if (VirtualJoystick.vjCanvas) {
  88183. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88184. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88185. }
  88186. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88187. };
  88188. // injecting a canvas element on top of the canvas 3D game
  88189. if (!VirtualJoystick.vjCanvas) {
  88190. window.addEventListener("resize", this._onResize, false);
  88191. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88192. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88193. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88194. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88195. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88196. VirtualJoystick.vjCanvas.style.width = "100%";
  88197. VirtualJoystick.vjCanvas.style.height = "100%";
  88198. VirtualJoystick.vjCanvas.style.position = "absolute";
  88199. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88200. VirtualJoystick.vjCanvas.style.top = "0px";
  88201. VirtualJoystick.vjCanvas.style.left = "0px";
  88202. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88203. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88204. // Support for jQuery PEP polyfill
  88205. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88206. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88207. if (!context) {
  88208. throw new Error("Unable to create canvas for virtual joystick");
  88209. }
  88210. VirtualJoystick.vjCanvasContext = context;
  88211. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88212. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88213. document.body.appendChild(VirtualJoystick.vjCanvas);
  88214. }
  88215. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88216. this.pressed = false;
  88217. // default joystick color
  88218. this._joystickColor = "cyan";
  88219. this._joystickPointerID = -1;
  88220. // current joystick position
  88221. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88222. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88223. // origin joystick position
  88224. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88225. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88226. this._onPointerDownHandlerRef = function (evt) {
  88227. _this._onPointerDown(evt);
  88228. };
  88229. this._onPointerMoveHandlerRef = function (evt) {
  88230. _this._onPointerMove(evt);
  88231. };
  88232. this._onPointerUpHandlerRef = function (evt) {
  88233. _this._onPointerUp(evt);
  88234. };
  88235. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88236. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88237. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88238. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88239. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88240. evt.preventDefault(); // Disables system menu
  88241. }, false);
  88242. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88243. }
  88244. /**
  88245. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88246. * @param newJoystickSensibility defines the new sensibility
  88247. */
  88248. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88249. this._joystickSensibility = newJoystickSensibility;
  88250. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88251. };
  88252. VirtualJoystick.prototype._onPointerDown = function (e) {
  88253. var positionOnScreenCondition;
  88254. e.preventDefault();
  88255. if (this._leftJoystick === true) {
  88256. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88257. }
  88258. else {
  88259. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88260. }
  88261. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88262. // First contact will be dedicated to the virtual joystick
  88263. this._joystickPointerID = e.pointerId;
  88264. this._joystickPointerStartPos.x = e.clientX;
  88265. this._joystickPointerStartPos.y = e.clientY;
  88266. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88267. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88268. this._deltaJoystickVector.x = 0;
  88269. this._deltaJoystickVector.y = 0;
  88270. this.pressed = true;
  88271. this._touches.add(e.pointerId.toString(), e);
  88272. }
  88273. else {
  88274. // You can only trigger the action buttons with a joystick declared
  88275. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88276. this._action();
  88277. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88278. }
  88279. }
  88280. };
  88281. VirtualJoystick.prototype._onPointerMove = function (e) {
  88282. // If the current pointer is the one associated to the joystick (first touch contact)
  88283. if (this._joystickPointerID == e.pointerId) {
  88284. this._joystickPointerPos.x = e.clientX;
  88285. this._joystickPointerPos.y = e.clientY;
  88286. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88287. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88288. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88289. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88290. switch (this._axisTargetedByLeftAndRight) {
  88291. case JoystickAxis.X:
  88292. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88293. break;
  88294. case JoystickAxis.Y:
  88295. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88296. break;
  88297. case JoystickAxis.Z:
  88298. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88299. break;
  88300. }
  88301. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88302. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88303. switch (this._axisTargetedByUpAndDown) {
  88304. case JoystickAxis.X:
  88305. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88306. break;
  88307. case JoystickAxis.Y:
  88308. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88309. break;
  88310. case JoystickAxis.Z:
  88311. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88312. break;
  88313. }
  88314. }
  88315. else {
  88316. var data = this._touches.get(e.pointerId.toString());
  88317. if (data) {
  88318. data.x = e.clientX;
  88319. data.y = e.clientY;
  88320. }
  88321. }
  88322. };
  88323. VirtualJoystick.prototype._onPointerUp = function (e) {
  88324. if (this._joystickPointerID == e.pointerId) {
  88325. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88326. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88327. this._joystickPointerID = -1;
  88328. this.pressed = false;
  88329. }
  88330. else {
  88331. var touch = this._touches.get(e.pointerId.toString());
  88332. if (touch) {
  88333. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88334. }
  88335. }
  88336. this._deltaJoystickVector.x = 0;
  88337. this._deltaJoystickVector.y = 0;
  88338. this._touches.remove(e.pointerId.toString());
  88339. };
  88340. /**
  88341. * Change the color of the virtual joystick
  88342. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88343. */
  88344. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88345. this._joystickColor = newColor;
  88346. };
  88347. /**
  88348. * Defines a callback to call when the joystick is touched
  88349. * @param action defines the callback
  88350. */
  88351. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88352. this._action = action;
  88353. };
  88354. /**
  88355. * Defines which axis you'd like to control for left & right
  88356. * @param axis defines the axis to use
  88357. */
  88358. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88359. switch (axis) {
  88360. case JoystickAxis.X:
  88361. case JoystickAxis.Y:
  88362. case JoystickAxis.Z:
  88363. this._axisTargetedByLeftAndRight = axis;
  88364. break;
  88365. default:
  88366. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88367. break;
  88368. }
  88369. };
  88370. /**
  88371. * Defines which axis you'd like to control for up & down
  88372. * @param axis defines the axis to use
  88373. */
  88374. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  88375. switch (axis) {
  88376. case JoystickAxis.X:
  88377. case JoystickAxis.Y:
  88378. case JoystickAxis.Z:
  88379. this._axisTargetedByUpAndDown = axis;
  88380. break;
  88381. default:
  88382. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88383. break;
  88384. }
  88385. };
  88386. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  88387. var _this = this;
  88388. if (this.pressed) {
  88389. this._touches.forEach(function (key, touch) {
  88390. if (touch.pointerId === _this._joystickPointerID) {
  88391. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  88392. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  88393. VirtualJoystick.vjCanvasContext.beginPath();
  88394. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88395. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88396. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  88397. VirtualJoystick.vjCanvasContext.stroke();
  88398. VirtualJoystick.vjCanvasContext.closePath();
  88399. VirtualJoystick.vjCanvasContext.beginPath();
  88400. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88401. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88402. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  88403. VirtualJoystick.vjCanvasContext.stroke();
  88404. VirtualJoystick.vjCanvasContext.closePath();
  88405. VirtualJoystick.vjCanvasContext.beginPath();
  88406. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88407. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  88408. VirtualJoystick.vjCanvasContext.stroke();
  88409. VirtualJoystick.vjCanvasContext.closePath();
  88410. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  88411. }
  88412. else {
  88413. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88414. VirtualJoystick.vjCanvasContext.beginPath();
  88415. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  88416. VirtualJoystick.vjCanvasContext.beginPath();
  88417. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  88418. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88419. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  88420. VirtualJoystick.vjCanvasContext.stroke();
  88421. VirtualJoystick.vjCanvasContext.closePath();
  88422. touch.prevX = touch.x;
  88423. touch.prevY = touch.y;
  88424. }
  88425. ;
  88426. });
  88427. }
  88428. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88429. };
  88430. /**
  88431. * Release internal HTML canvas
  88432. */
  88433. VirtualJoystick.prototype.releaseCanvas = function () {
  88434. if (VirtualJoystick.vjCanvas) {
  88435. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  88436. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  88437. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  88438. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  88439. window.removeEventListener("resize", this._onResize);
  88440. document.body.removeChild(VirtualJoystick.vjCanvas);
  88441. VirtualJoystick.vjCanvas = null;
  88442. }
  88443. };
  88444. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  88445. VirtualJoystick._globalJoystickIndex = 0;
  88446. return VirtualJoystick;
  88447. }());
  88448. BABYLON.VirtualJoystick = VirtualJoystick;
  88449. })(BABYLON || (BABYLON = {}));
  88450. //# sourceMappingURL=babylon.virtualJoystick.js.map
  88451. var BABYLON;
  88452. (function (BABYLON) {
  88453. // We're mainly based on the logic defined into the FreeCamera code
  88454. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  88455. __extends(VirtualJoysticksCamera, _super);
  88456. function VirtualJoysticksCamera(name, position, scene) {
  88457. var _this = _super.call(this, name, position, scene) || this;
  88458. _this.inputs.addVirtualJoystick();
  88459. return _this;
  88460. }
  88461. VirtualJoysticksCamera.prototype.getClassName = function () {
  88462. return "VirtualJoysticksCamera";
  88463. };
  88464. return VirtualJoysticksCamera;
  88465. }(BABYLON.FreeCamera));
  88466. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  88467. })(BABYLON || (BABYLON = {}));
  88468. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  88469. var BABYLON;
  88470. (function (BABYLON) {
  88471. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  88472. function FreeCameraVirtualJoystickInput() {
  88473. }
  88474. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  88475. return this._leftjoystick;
  88476. };
  88477. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  88478. return this._rightjoystick;
  88479. };
  88480. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  88481. if (this._leftjoystick) {
  88482. var camera = this.camera;
  88483. var speed = camera._computeLocalCameraSpeed() * 50;
  88484. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  88485. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  88486. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  88487. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  88488. if (!this._leftjoystick.pressed) {
  88489. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  88490. }
  88491. if (!this._rightjoystick.pressed) {
  88492. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  88493. }
  88494. }
  88495. };
  88496. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  88497. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  88498. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  88499. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  88500. this._leftjoystick.setJoystickSensibility(0.15);
  88501. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  88502. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  88503. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  88504. this._rightjoystick.reverseUpDown = true;
  88505. this._rightjoystick.setJoystickSensibility(0.05);
  88506. this._rightjoystick.setJoystickColor("yellow");
  88507. };
  88508. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  88509. this._leftjoystick.releaseCanvas();
  88510. this._rightjoystick.releaseCanvas();
  88511. };
  88512. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  88513. return "FreeCameraVirtualJoystickInput";
  88514. };
  88515. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  88516. return "virtualJoystick";
  88517. };
  88518. return FreeCameraVirtualJoystickInput;
  88519. }());
  88520. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  88521. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  88522. })(BABYLON || (BABYLON = {}));
  88523. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  88524. var BABYLON;
  88525. (function (BABYLON) {
  88526. var SimplificationSettings = /** @class */ (function () {
  88527. function SimplificationSettings(quality, distance, optimizeMesh) {
  88528. this.quality = quality;
  88529. this.distance = distance;
  88530. this.optimizeMesh = optimizeMesh;
  88531. }
  88532. return SimplificationSettings;
  88533. }());
  88534. BABYLON.SimplificationSettings = SimplificationSettings;
  88535. var SimplificationQueue = /** @class */ (function () {
  88536. function SimplificationQueue() {
  88537. this.running = false;
  88538. this._simplificationArray = [];
  88539. }
  88540. SimplificationQueue.prototype.addTask = function (task) {
  88541. this._simplificationArray.push(task);
  88542. };
  88543. SimplificationQueue.prototype.executeNext = function () {
  88544. var task = this._simplificationArray.pop();
  88545. if (task) {
  88546. this.running = true;
  88547. this.runSimplification(task);
  88548. }
  88549. else {
  88550. this.running = false;
  88551. }
  88552. };
  88553. SimplificationQueue.prototype.runSimplification = function (task) {
  88554. var _this = this;
  88555. if (task.parallelProcessing) {
  88556. //parallel simplifier
  88557. task.settings.forEach(function (setting) {
  88558. var simplifier = _this.getSimplifier(task);
  88559. simplifier.simplify(setting, function (newMesh) {
  88560. task.mesh.addLODLevel(setting.distance, newMesh);
  88561. newMesh.isVisible = true;
  88562. //check if it is the last
  88563. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  88564. //all done, run the success callback.
  88565. task.successCallback();
  88566. }
  88567. _this.executeNext();
  88568. });
  88569. });
  88570. }
  88571. else {
  88572. //single simplifier.
  88573. var simplifier = this.getSimplifier(task);
  88574. var runDecimation = function (setting, callback) {
  88575. simplifier.simplify(setting, function (newMesh) {
  88576. task.mesh.addLODLevel(setting.distance, newMesh);
  88577. newMesh.isVisible = true;
  88578. //run the next quality level
  88579. callback();
  88580. });
  88581. };
  88582. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  88583. runDecimation(task.settings[loop.index], function () {
  88584. loop.executeNext();
  88585. });
  88586. }, function () {
  88587. //execution ended, run the success callback.
  88588. if (task.successCallback) {
  88589. task.successCallback();
  88590. }
  88591. _this.executeNext();
  88592. });
  88593. }
  88594. };
  88595. SimplificationQueue.prototype.getSimplifier = function (task) {
  88596. switch (task.simplificationType) {
  88597. case SimplificationType.QUADRATIC:
  88598. default:
  88599. return new QuadraticErrorSimplification(task.mesh);
  88600. }
  88601. };
  88602. return SimplificationQueue;
  88603. }());
  88604. BABYLON.SimplificationQueue = SimplificationQueue;
  88605. /**
  88606. * The implemented types of simplification
  88607. * At the moment only Quadratic Error Decimation is implemented
  88608. */
  88609. var SimplificationType;
  88610. (function (SimplificationType) {
  88611. /** Quadratic error decimation */
  88612. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88613. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88614. var DecimationTriangle = /** @class */ (function () {
  88615. function DecimationTriangle(vertices) {
  88616. this.vertices = vertices;
  88617. this.error = new Array(4);
  88618. this.deleted = false;
  88619. this.isDirty = false;
  88620. this.deletePending = false;
  88621. this.borderFactor = 0;
  88622. }
  88623. return DecimationTriangle;
  88624. }());
  88625. BABYLON.DecimationTriangle = DecimationTriangle;
  88626. var DecimationVertex = /** @class */ (function () {
  88627. function DecimationVertex(position, id) {
  88628. this.position = position;
  88629. this.id = id;
  88630. this.isBorder = true;
  88631. this.q = new QuadraticMatrix();
  88632. this.triangleCount = 0;
  88633. this.triangleStart = 0;
  88634. this.originalOffsets = [];
  88635. }
  88636. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88637. this.position.copyFrom(newPosition);
  88638. };
  88639. return DecimationVertex;
  88640. }());
  88641. BABYLON.DecimationVertex = DecimationVertex;
  88642. var QuadraticMatrix = /** @class */ (function () {
  88643. function QuadraticMatrix(data) {
  88644. this.data = new Array(10);
  88645. for (var i = 0; i < 10; ++i) {
  88646. if (data && data[i]) {
  88647. this.data[i] = data[i];
  88648. }
  88649. else {
  88650. this.data[i] = 0;
  88651. }
  88652. }
  88653. }
  88654. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88655. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88656. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88657. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88658. return det;
  88659. };
  88660. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88661. for (var i = 0; i < 10; ++i) {
  88662. this.data[i] += matrix.data[i];
  88663. }
  88664. };
  88665. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88666. for (var i = 0; i < 10; ++i) {
  88667. this.data[i] += data[i];
  88668. }
  88669. };
  88670. QuadraticMatrix.prototype.add = function (matrix) {
  88671. var m = new QuadraticMatrix();
  88672. for (var i = 0; i < 10; ++i) {
  88673. m.data[i] = this.data[i] + matrix.data[i];
  88674. }
  88675. return m;
  88676. };
  88677. QuadraticMatrix.FromData = function (a, b, c, d) {
  88678. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88679. };
  88680. //returning an array to avoid garbage collection
  88681. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88682. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88683. };
  88684. return QuadraticMatrix;
  88685. }());
  88686. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88687. var Reference = /** @class */ (function () {
  88688. function Reference(vertexId, triangleId) {
  88689. this.vertexId = vertexId;
  88690. this.triangleId = triangleId;
  88691. }
  88692. return Reference;
  88693. }());
  88694. BABYLON.Reference = Reference;
  88695. /**
  88696. * An implementation of the Quadratic Error simplification algorithm.
  88697. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88698. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88699. * @author RaananW
  88700. */
  88701. var QuadraticErrorSimplification = /** @class */ (function () {
  88702. function QuadraticErrorSimplification(_mesh) {
  88703. this._mesh = _mesh;
  88704. this.syncIterations = 5000;
  88705. this.aggressiveness = 7;
  88706. this.decimationIterations = 100;
  88707. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88708. }
  88709. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88710. var _this = this;
  88711. this.initDecimatedMesh();
  88712. //iterating through the submeshes array, one after the other.
  88713. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88714. _this.initWithMesh(loop.index, function () {
  88715. _this.runDecimation(settings, loop.index, function () {
  88716. loop.executeNext();
  88717. });
  88718. }, settings.optimizeMesh);
  88719. }, function () {
  88720. setTimeout(function () {
  88721. successCallback(_this._reconstructedMesh);
  88722. }, 0);
  88723. });
  88724. };
  88725. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88726. var _this = this;
  88727. var targetCount = ~~(this.triangles.length * settings.quality);
  88728. var deletedTriangles = 0;
  88729. var triangleCount = this.triangles.length;
  88730. var iterationFunction = function (iteration, callback) {
  88731. setTimeout(function () {
  88732. if (iteration % 5 === 0) {
  88733. _this.updateMesh(iteration === 0);
  88734. }
  88735. for (var i = 0; i < _this.triangles.length; ++i) {
  88736. _this.triangles[i].isDirty = false;
  88737. }
  88738. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88739. var trianglesIterator = function (i) {
  88740. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88741. var t = _this.triangles[tIdx];
  88742. if (!t)
  88743. return;
  88744. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88745. return;
  88746. }
  88747. for (var j = 0; j < 3; ++j) {
  88748. if (t.error[j] < threshold) {
  88749. var deleted0 = [];
  88750. var deleted1 = [];
  88751. var v0 = t.vertices[j];
  88752. var v1 = t.vertices[(j + 1) % 3];
  88753. if (v0.isBorder || v1.isBorder)
  88754. continue;
  88755. var p = BABYLON.Vector3.Zero();
  88756. var n = BABYLON.Vector3.Zero();
  88757. var uv = BABYLON.Vector2.Zero();
  88758. var color = new BABYLON.Color4(0, 0, 0, 1);
  88759. _this.calculateError(v0, v1, p, n, uv, color);
  88760. var delTr = new Array();
  88761. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88762. continue;
  88763. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88764. continue;
  88765. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88766. continue;
  88767. var uniqueArray = new Array();
  88768. delTr.forEach(function (deletedT) {
  88769. if (uniqueArray.indexOf(deletedT) === -1) {
  88770. deletedT.deletePending = true;
  88771. uniqueArray.push(deletedT);
  88772. }
  88773. });
  88774. if (uniqueArray.length % 2 !== 0) {
  88775. continue;
  88776. }
  88777. v0.q = v1.q.add(v0.q);
  88778. v0.updatePosition(p);
  88779. var tStart = _this.references.length;
  88780. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88781. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88782. var tCount = _this.references.length - tStart;
  88783. if (tCount <= v0.triangleCount) {
  88784. if (tCount) {
  88785. for (var c = 0; c < tCount; c++) {
  88786. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88787. }
  88788. }
  88789. }
  88790. else {
  88791. v0.triangleStart = tStart;
  88792. }
  88793. v0.triangleCount = tCount;
  88794. break;
  88795. }
  88796. }
  88797. };
  88798. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88799. }, 0);
  88800. };
  88801. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88802. if (triangleCount - deletedTriangles <= targetCount)
  88803. loop.breakLoop();
  88804. else {
  88805. iterationFunction(loop.index, function () {
  88806. loop.executeNext();
  88807. });
  88808. }
  88809. }, function () {
  88810. setTimeout(function () {
  88811. //reconstruct this part of the mesh
  88812. _this.reconstructMesh(submeshIndex);
  88813. successCallback();
  88814. }, 0);
  88815. });
  88816. };
  88817. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88818. var _this = this;
  88819. this.vertices = [];
  88820. this.triangles = [];
  88821. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88822. var indices = this._mesh.getIndices();
  88823. var submesh = this._mesh.subMeshes[submeshIndex];
  88824. var findInVertices = function (positionToSearch) {
  88825. if (optimizeMesh) {
  88826. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88827. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88828. return _this.vertices[ii];
  88829. }
  88830. }
  88831. }
  88832. return null;
  88833. };
  88834. var vertexReferences = [];
  88835. var vertexInit = function (i) {
  88836. if (!positionData) {
  88837. return;
  88838. }
  88839. var offset = i + submesh.verticesStart;
  88840. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88841. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88842. vertex.originalOffsets.push(offset);
  88843. if (vertex.id === _this.vertices.length) {
  88844. _this.vertices.push(vertex);
  88845. }
  88846. vertexReferences.push(vertex.id);
  88847. };
  88848. //var totalVertices = mesh.getTotalVertices();
  88849. var totalVertices = submesh.verticesCount;
  88850. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88851. var indicesInit = function (i) {
  88852. if (!indices) {
  88853. return;
  88854. }
  88855. var offset = (submesh.indexStart / 3) + i;
  88856. var pos = (offset * 3);
  88857. var i0 = indices[pos + 0];
  88858. var i1 = indices[pos + 1];
  88859. var i2 = indices[pos + 2];
  88860. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88861. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88862. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88863. var triangle = new DecimationTriangle([v0, v1, v2]);
  88864. triangle.originalOffset = pos;
  88865. _this.triangles.push(triangle);
  88866. };
  88867. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88868. _this.init(callback);
  88869. });
  88870. });
  88871. };
  88872. QuadraticErrorSimplification.prototype.init = function (callback) {
  88873. var _this = this;
  88874. var triangleInit1 = function (i) {
  88875. var t = _this.triangles[i];
  88876. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88877. for (var j = 0; j < 3; j++) {
  88878. 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))));
  88879. }
  88880. };
  88881. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88882. var triangleInit2 = function (i) {
  88883. var t = _this.triangles[i];
  88884. for (var j = 0; j < 3; ++j) {
  88885. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88886. }
  88887. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88888. };
  88889. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88890. callback();
  88891. });
  88892. });
  88893. };
  88894. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  88895. var newTriangles = [];
  88896. var i;
  88897. for (i = 0; i < this.vertices.length; ++i) {
  88898. this.vertices[i].triangleCount = 0;
  88899. }
  88900. var t;
  88901. var j;
  88902. for (i = 0; i < this.triangles.length; ++i) {
  88903. if (!this.triangles[i].deleted) {
  88904. t = this.triangles[i];
  88905. for (j = 0; j < 3; ++j) {
  88906. t.vertices[j].triangleCount = 1;
  88907. }
  88908. newTriangles.push(t);
  88909. }
  88910. }
  88911. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88912. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88913. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88914. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88915. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88916. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88917. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88918. var vertexCount = 0;
  88919. for (i = 0; i < this.vertices.length; ++i) {
  88920. var vertex = this.vertices[i];
  88921. vertex.id = vertexCount;
  88922. if (vertex.triangleCount) {
  88923. vertex.originalOffsets.forEach(function (originalOffset) {
  88924. if (!normalData) {
  88925. return;
  88926. }
  88927. newPositionData.push(vertex.position.x);
  88928. newPositionData.push(vertex.position.y);
  88929. newPositionData.push(vertex.position.z);
  88930. newNormalData.push(normalData[originalOffset * 3]);
  88931. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88932. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88933. if (uvs && uvs.length) {
  88934. newUVsData.push(uvs[(originalOffset * 2)]);
  88935. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88936. }
  88937. else if (colorsData && colorsData.length) {
  88938. newColorsData.push(colorsData[(originalOffset * 4)]);
  88939. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88940. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88941. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88942. }
  88943. ++vertexCount;
  88944. });
  88945. }
  88946. }
  88947. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88948. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88949. var submeshesArray = this._reconstructedMesh.subMeshes;
  88950. this._reconstructedMesh.subMeshes = [];
  88951. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88952. var originalIndices = this._mesh.getIndices();
  88953. for (i = 0; i < newTriangles.length; ++i) {
  88954. t = newTriangles[i]; //now get the new referencing point for each vertex
  88955. [0, 1, 2].forEach(function (idx) {
  88956. var id = originalIndices[t.originalOffset + idx];
  88957. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88958. if (offset < 0)
  88959. offset = 0;
  88960. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88961. });
  88962. }
  88963. //overwriting the old vertex buffers and indices.
  88964. this._reconstructedMesh.setIndices(newIndicesArray);
  88965. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88966. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88967. if (newUVsData.length > 0)
  88968. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88969. if (newColorsData.length > 0)
  88970. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88971. //create submesh
  88972. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88973. if (submeshIndex > 0) {
  88974. this._reconstructedMesh.subMeshes = [];
  88975. submeshesArray.forEach(function (submesh) {
  88976. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88977. });
  88978. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88979. }
  88980. };
  88981. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88982. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88983. this._reconstructedMesh.material = this._mesh.material;
  88984. this._reconstructedMesh.parent = this._mesh.parent;
  88985. this._reconstructedMesh.isVisible = false;
  88986. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88987. };
  88988. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88989. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88990. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88991. if (t.deleted)
  88992. continue;
  88993. var s = this.references[vertex1.triangleStart + i].vertexId;
  88994. var v1 = t.vertices[(s + 1) % 3];
  88995. var v2 = t.vertices[(s + 2) % 3];
  88996. if ((v1 === vertex2 || v2 === vertex2)) {
  88997. deletedArray[i] = true;
  88998. delTr.push(t);
  88999. continue;
  89000. }
  89001. var d1 = v1.position.subtract(point);
  89002. d1 = d1.normalize();
  89003. var d2 = v2.position.subtract(point);
  89004. d2 = d2.normalize();
  89005. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89006. return true;
  89007. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89008. deletedArray[i] = false;
  89009. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89010. return true;
  89011. }
  89012. return false;
  89013. };
  89014. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89015. var newDeleted = deletedTriangles;
  89016. for (var i = 0; i < vertex.triangleCount; ++i) {
  89017. var ref = this.references[vertex.triangleStart + i];
  89018. var t = this.triangles[ref.triangleId];
  89019. if (t.deleted)
  89020. continue;
  89021. if (deletedArray[i] && t.deletePending) {
  89022. t.deleted = true;
  89023. newDeleted++;
  89024. continue;
  89025. }
  89026. t.vertices[ref.vertexId] = origVertex;
  89027. t.isDirty = true;
  89028. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89029. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89030. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89031. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89032. this.references.push(ref);
  89033. }
  89034. return newDeleted;
  89035. };
  89036. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89037. for (var i = 0; i < this.vertices.length; ++i) {
  89038. var vCount = [];
  89039. var vId = [];
  89040. var v = this.vertices[i];
  89041. var j;
  89042. for (j = 0; j < v.triangleCount; ++j) {
  89043. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89044. for (var ii = 0; ii < 3; ii++) {
  89045. var ofs = 0;
  89046. var vv = triangle.vertices[ii];
  89047. while (ofs < vCount.length) {
  89048. if (vId[ofs] === vv.id)
  89049. break;
  89050. ++ofs;
  89051. }
  89052. if (ofs === vCount.length) {
  89053. vCount.push(1);
  89054. vId.push(vv.id);
  89055. }
  89056. else {
  89057. vCount[ofs]++;
  89058. }
  89059. }
  89060. }
  89061. for (j = 0; j < vCount.length; ++j) {
  89062. if (vCount[j] === 1) {
  89063. this.vertices[vId[j]].isBorder = true;
  89064. }
  89065. else {
  89066. this.vertices[vId[j]].isBorder = false;
  89067. }
  89068. }
  89069. }
  89070. };
  89071. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89072. if (identifyBorders === void 0) { identifyBorders = false; }
  89073. var i;
  89074. if (!identifyBorders) {
  89075. var newTrianglesVector = [];
  89076. for (i = 0; i < this.triangles.length; ++i) {
  89077. if (!this.triangles[i].deleted) {
  89078. newTrianglesVector.push(this.triangles[i]);
  89079. }
  89080. }
  89081. this.triangles = newTrianglesVector;
  89082. }
  89083. for (i = 0; i < this.vertices.length; ++i) {
  89084. this.vertices[i].triangleCount = 0;
  89085. this.vertices[i].triangleStart = 0;
  89086. }
  89087. var t;
  89088. var j;
  89089. var v;
  89090. for (i = 0; i < this.triangles.length; ++i) {
  89091. t = this.triangles[i];
  89092. for (j = 0; j < 3; ++j) {
  89093. v = t.vertices[j];
  89094. v.triangleCount++;
  89095. }
  89096. }
  89097. var tStart = 0;
  89098. for (i = 0; i < this.vertices.length; ++i) {
  89099. this.vertices[i].triangleStart = tStart;
  89100. tStart += this.vertices[i].triangleCount;
  89101. this.vertices[i].triangleCount = 0;
  89102. }
  89103. var newReferences = new Array(this.triangles.length * 3);
  89104. for (i = 0; i < this.triangles.length; ++i) {
  89105. t = this.triangles[i];
  89106. for (j = 0; j < 3; ++j) {
  89107. v = t.vertices[j];
  89108. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89109. v.triangleCount++;
  89110. }
  89111. }
  89112. this.references = newReferences;
  89113. if (identifyBorders) {
  89114. this.identifyBorder();
  89115. }
  89116. };
  89117. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89118. var x = point.x;
  89119. var y = point.y;
  89120. var z = point.z;
  89121. 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
  89122. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89123. };
  89124. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89125. var q = vertex1.q.add(vertex2.q);
  89126. var border = vertex1.isBorder && vertex2.isBorder;
  89127. var error = 0;
  89128. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89129. if (qDet !== 0 && !border) {
  89130. if (!pointResult) {
  89131. pointResult = BABYLON.Vector3.Zero();
  89132. }
  89133. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89134. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89135. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89136. error = this.vertexError(q, pointResult);
  89137. }
  89138. else {
  89139. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89140. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89141. var error1 = this.vertexError(q, vertex1.position);
  89142. var error2 = this.vertexError(q, vertex2.position);
  89143. var error3 = this.vertexError(q, p3);
  89144. error = Math.min(error1, error2, error3);
  89145. if (error === error1) {
  89146. if (pointResult) {
  89147. pointResult.copyFrom(vertex1.position);
  89148. }
  89149. }
  89150. else if (error === error2) {
  89151. if (pointResult) {
  89152. pointResult.copyFrom(vertex2.position);
  89153. }
  89154. }
  89155. else {
  89156. if (pointResult) {
  89157. pointResult.copyFrom(p3);
  89158. }
  89159. }
  89160. }
  89161. return error;
  89162. };
  89163. return QuadraticErrorSimplification;
  89164. }());
  89165. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89166. })(BABYLON || (BABYLON = {}));
  89167. //# sourceMappingURL=babylon.meshSimplification.js.map
  89168. var BABYLON;
  89169. (function (BABYLON) {
  89170. var MeshLODLevel = /** @class */ (function () {
  89171. function MeshLODLevel(distance, mesh) {
  89172. this.distance = distance;
  89173. this.mesh = mesh;
  89174. }
  89175. return MeshLODLevel;
  89176. }());
  89177. BABYLON.MeshLODLevel = MeshLODLevel;
  89178. })(BABYLON || (BABYLON = {}));
  89179. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89180. var BABYLON;
  89181. (function (BABYLON) {
  89182. /**
  89183. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89184. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89185. */
  89186. var SceneOptimization = /** @class */ (function () {
  89187. /**
  89188. * Creates the SceneOptimization object
  89189. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89190. * @param desc defines the description associated with the optimization
  89191. */
  89192. function SceneOptimization(
  89193. /**
  89194. * Defines the priority of this optimization (0 by default which means first in the list)
  89195. */
  89196. priority) {
  89197. if (priority === void 0) { priority = 0; }
  89198. this.priority = priority;
  89199. }
  89200. /**
  89201. * Gets a string describing the action executed by the current optimization
  89202. * @returns description string
  89203. */
  89204. SceneOptimization.prototype.getDescription = function () {
  89205. return "";
  89206. };
  89207. /**
  89208. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89209. * @param scene defines the current scene where to apply this optimization
  89210. * @param optimizer defines the current optimizer
  89211. * @returns true if everything that can be done was applied
  89212. */
  89213. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89214. return true;
  89215. };
  89216. ;
  89217. return SceneOptimization;
  89218. }());
  89219. BABYLON.SceneOptimization = SceneOptimization;
  89220. /**
  89221. * Defines an optimization used to reduce the size of render target textures
  89222. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89223. */
  89224. var TextureOptimization = /** @class */ (function (_super) {
  89225. __extends(TextureOptimization, _super);
  89226. /**
  89227. * Creates the TextureOptimization object
  89228. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89229. * @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
  89230. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89231. */
  89232. function TextureOptimization(
  89233. /**
  89234. * Defines the priority of this optimization (0 by default which means first in the list)
  89235. */
  89236. priority,
  89237. /**
  89238. * 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
  89239. */
  89240. maximumSize,
  89241. /**
  89242. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89243. */
  89244. step) {
  89245. if (priority === void 0) { priority = 0; }
  89246. if (maximumSize === void 0) { maximumSize = 1024; }
  89247. if (step === void 0) { step = 0.5; }
  89248. var _this = _super.call(this, priority) || this;
  89249. _this.priority = priority;
  89250. _this.maximumSize = maximumSize;
  89251. _this.step = step;
  89252. return _this;
  89253. }
  89254. /**
  89255. * Gets a string describing the action executed by the current optimization
  89256. * @returns description string
  89257. */
  89258. TextureOptimization.prototype.getDescription = function () {
  89259. return "Reducing render target texture size to " + this.maximumSize;
  89260. };
  89261. /**
  89262. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89263. * @param scene defines the current scene where to apply this optimization
  89264. * @param optimizer defines the current optimizer
  89265. * @returns true if everything that can be done was applied
  89266. */
  89267. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89268. var allDone = true;
  89269. for (var index = 0; index < scene.textures.length; index++) {
  89270. var texture = scene.textures[index];
  89271. if (!texture.canRescale || texture.getContext) {
  89272. continue;
  89273. }
  89274. var currentSize = texture.getSize();
  89275. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89276. if (maxDimension > this.maximumSize) {
  89277. texture.scale(this.step);
  89278. allDone = false;
  89279. }
  89280. }
  89281. return allDone;
  89282. };
  89283. return TextureOptimization;
  89284. }(SceneOptimization));
  89285. BABYLON.TextureOptimization = TextureOptimization;
  89286. /**
  89287. * Defines an optimization used to increase or decrease the rendering resolution
  89288. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89289. */
  89290. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89291. __extends(HardwareScalingOptimization, _super);
  89292. /**
  89293. * Creates the HardwareScalingOptimization object
  89294. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89295. * @param maximumScale defines the maximum scale to use (2 by default)
  89296. * @param step defines the step to use between two passes (0.5 by default)
  89297. */
  89298. function HardwareScalingOptimization(
  89299. /**
  89300. * Defines the priority of this optimization (0 by default which means first in the list)
  89301. */
  89302. priority,
  89303. /**
  89304. * Defines the maximum scale to use (2 by default)
  89305. */
  89306. maximumScale,
  89307. /**
  89308. * Defines the step to use between two passes (0.5 by default)
  89309. */
  89310. step) {
  89311. if (priority === void 0) { priority = 0; }
  89312. if (maximumScale === void 0) { maximumScale = 2; }
  89313. if (step === void 0) { step = 0.25; }
  89314. var _this = _super.call(this, priority) || this;
  89315. _this.priority = priority;
  89316. _this.maximumScale = maximumScale;
  89317. _this.step = step;
  89318. _this._currentScale = -1;
  89319. _this._directionOffset = 1;
  89320. return _this;
  89321. }
  89322. /**
  89323. * Gets a string describing the action executed by the current optimization
  89324. * @return description string
  89325. */
  89326. HardwareScalingOptimization.prototype.getDescription = function () {
  89327. return "Setting hardware scaling level to " + this._currentScale;
  89328. };
  89329. /**
  89330. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89331. * @param scene defines the current scene where to apply this optimization
  89332. * @param optimizer defines the current optimizer
  89333. * @returns true if everything that can be done was applied
  89334. */
  89335. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89336. if (this._currentScale === -1) {
  89337. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89338. if (this._currentScale > this.maximumScale) {
  89339. this._directionOffset = -1;
  89340. }
  89341. }
  89342. this._currentScale += this._directionOffset * this.step;
  89343. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89344. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89345. };
  89346. ;
  89347. return HardwareScalingOptimization;
  89348. }(SceneOptimization));
  89349. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89350. /**
  89351. * Defines an optimization used to remove shadows
  89352. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89353. */
  89354. var ShadowsOptimization = /** @class */ (function (_super) {
  89355. __extends(ShadowsOptimization, _super);
  89356. function ShadowsOptimization() {
  89357. return _super !== null && _super.apply(this, arguments) || this;
  89358. }
  89359. /**
  89360. * Gets a string describing the action executed by the current optimization
  89361. * @return description string
  89362. */
  89363. ShadowsOptimization.prototype.getDescription = function () {
  89364. return "Turning shadows on/off";
  89365. };
  89366. /**
  89367. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89368. * @param scene defines the current scene where to apply this optimization
  89369. * @param optimizer defines the current optimizer
  89370. * @returns true if everything that can be done was applied
  89371. */
  89372. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89373. scene.shadowsEnabled = optimizer.isInImprovementMode;
  89374. return true;
  89375. };
  89376. ;
  89377. return ShadowsOptimization;
  89378. }(SceneOptimization));
  89379. BABYLON.ShadowsOptimization = ShadowsOptimization;
  89380. /**
  89381. * Defines an optimization used to turn post-processes off
  89382. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89383. */
  89384. var PostProcessesOptimization = /** @class */ (function (_super) {
  89385. __extends(PostProcessesOptimization, _super);
  89386. function PostProcessesOptimization() {
  89387. return _super !== null && _super.apply(this, arguments) || this;
  89388. }
  89389. /**
  89390. * Gets a string describing the action executed by the current optimization
  89391. * @return description string
  89392. */
  89393. PostProcessesOptimization.prototype.getDescription = function () {
  89394. return "Turning post-processes on/off";
  89395. };
  89396. /**
  89397. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89398. * @param scene defines the current scene where to apply this optimization
  89399. * @param optimizer defines the current optimizer
  89400. * @returns true if everything that can be done was applied
  89401. */
  89402. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  89403. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  89404. return true;
  89405. };
  89406. ;
  89407. return PostProcessesOptimization;
  89408. }(SceneOptimization));
  89409. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  89410. /**
  89411. * Defines an optimization used to turn lens flares off
  89412. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89413. */
  89414. var LensFlaresOptimization = /** @class */ (function (_super) {
  89415. __extends(LensFlaresOptimization, _super);
  89416. function LensFlaresOptimization() {
  89417. return _super !== null && _super.apply(this, arguments) || this;
  89418. }
  89419. /**
  89420. * Gets a string describing the action executed by the current optimization
  89421. * @return description string
  89422. */
  89423. LensFlaresOptimization.prototype.getDescription = function () {
  89424. return "Turning lens flares on/off";
  89425. };
  89426. /**
  89427. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89428. * @param scene defines the current scene where to apply this optimization
  89429. * @param optimizer defines the current optimizer
  89430. * @returns true if everything that can be done was applied
  89431. */
  89432. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  89433. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  89434. return true;
  89435. };
  89436. ;
  89437. return LensFlaresOptimization;
  89438. }(SceneOptimization));
  89439. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  89440. /**
  89441. * Defines an optimization based on user defined callback.
  89442. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89443. */
  89444. var CustomOptimization = /** @class */ (function (_super) {
  89445. __extends(CustomOptimization, _super);
  89446. function CustomOptimization() {
  89447. return _super !== null && _super.apply(this, arguments) || this;
  89448. }
  89449. /**
  89450. * Gets a string describing the action executed by the current optimization
  89451. * @returns description string
  89452. */
  89453. CustomOptimization.prototype.getDescription = function () {
  89454. if (this.onGetDescription) {
  89455. return this.onGetDescription();
  89456. }
  89457. return "Running user defined callback";
  89458. };
  89459. /**
  89460. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89461. * @param scene defines the current scene where to apply this optimization
  89462. * @param optimizer defines the current optimizer
  89463. * @returns true if everything that can be done was applied
  89464. */
  89465. CustomOptimization.prototype.apply = function (scene, optimizer) {
  89466. if (this.onApply) {
  89467. return this.onApply(scene, optimizer);
  89468. }
  89469. return true;
  89470. };
  89471. ;
  89472. return CustomOptimization;
  89473. }(SceneOptimization));
  89474. BABYLON.CustomOptimization = CustomOptimization;
  89475. /**
  89476. * Defines an optimization used to turn particles off
  89477. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89478. */
  89479. var ParticlesOptimization = /** @class */ (function (_super) {
  89480. __extends(ParticlesOptimization, _super);
  89481. function ParticlesOptimization() {
  89482. return _super !== null && _super.apply(this, arguments) || this;
  89483. }
  89484. /**
  89485. * Gets a string describing the action executed by the current optimization
  89486. * @return description string
  89487. */
  89488. ParticlesOptimization.prototype.getDescription = function () {
  89489. return "Turning particles on/off";
  89490. };
  89491. /**
  89492. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89493. * @param scene defines the current scene where to apply this optimization
  89494. * @param optimizer defines the current optimizer
  89495. * @returns true if everything that can be done was applied
  89496. */
  89497. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  89498. scene.particlesEnabled = optimizer.isInImprovementMode;
  89499. return true;
  89500. };
  89501. ;
  89502. return ParticlesOptimization;
  89503. }(SceneOptimization));
  89504. BABYLON.ParticlesOptimization = ParticlesOptimization;
  89505. /**
  89506. * Defines an optimization used to turn render targets off
  89507. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89508. */
  89509. var RenderTargetsOptimization = /** @class */ (function (_super) {
  89510. __extends(RenderTargetsOptimization, _super);
  89511. function RenderTargetsOptimization() {
  89512. return _super !== null && _super.apply(this, arguments) || this;
  89513. }
  89514. /**
  89515. * Gets a string describing the action executed by the current optimization
  89516. * @return description string
  89517. */
  89518. RenderTargetsOptimization.prototype.getDescription = function () {
  89519. return "Turning render targets off";
  89520. };
  89521. /**
  89522. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89523. * @param scene defines the current scene where to apply this optimization
  89524. * @param optimizer defines the current optimizer
  89525. * @returns true if everything that can be done was applied
  89526. */
  89527. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  89528. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  89529. return true;
  89530. };
  89531. ;
  89532. return RenderTargetsOptimization;
  89533. }(SceneOptimization));
  89534. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  89535. /**
  89536. * Defines an optimization used to merge meshes with compatible materials
  89537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89538. */
  89539. var MergeMeshesOptimization = /** @class */ (function (_super) {
  89540. __extends(MergeMeshesOptimization, _super);
  89541. function MergeMeshesOptimization() {
  89542. var _this = _super !== null && _super.apply(this, arguments) || this;
  89543. _this._canBeMerged = function (abstractMesh) {
  89544. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  89545. return false;
  89546. }
  89547. var mesh = abstractMesh;
  89548. if (!mesh.isVisible || !mesh.isEnabled()) {
  89549. return false;
  89550. }
  89551. if (mesh.instances.length > 0) {
  89552. return false;
  89553. }
  89554. if (mesh.skeleton || mesh.hasLODLevels) {
  89555. return false;
  89556. }
  89557. if (mesh.parent) {
  89558. return false;
  89559. }
  89560. return true;
  89561. };
  89562. return _this;
  89563. }
  89564. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  89565. /**
  89566. * Gets or sets a boolean which defines if optimization octree has to be updated
  89567. */
  89568. get: function () {
  89569. return MergeMeshesOptimization._UpdateSelectionTree;
  89570. },
  89571. /**
  89572. * Gets or sets a boolean which defines if optimization octree has to be updated
  89573. */
  89574. set: function (value) {
  89575. MergeMeshesOptimization._UpdateSelectionTree = value;
  89576. },
  89577. enumerable: true,
  89578. configurable: true
  89579. });
  89580. /**
  89581. * Gets a string describing the action executed by the current optimization
  89582. * @return description string
  89583. */
  89584. MergeMeshesOptimization.prototype.getDescription = function () {
  89585. return "Merging similar meshes together";
  89586. };
  89587. /**
  89588. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89589. * @param scene defines the current scene where to apply this optimization
  89590. * @param optimizer defines the current optimizer
  89591. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  89592. * @returns true if everything that can be done was applied
  89593. */
  89594. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  89595. var globalPool = scene.meshes.slice(0);
  89596. var globalLength = globalPool.length;
  89597. for (var index = 0; index < globalLength; index++) {
  89598. var currentPool = new Array();
  89599. var current = globalPool[index];
  89600. // Checks
  89601. if (!this._canBeMerged(current)) {
  89602. continue;
  89603. }
  89604. currentPool.push(current);
  89605. // Find compatible meshes
  89606. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89607. var otherMesh = globalPool[subIndex];
  89608. if (!this._canBeMerged(otherMesh)) {
  89609. continue;
  89610. }
  89611. if (otherMesh.material !== current.material) {
  89612. continue;
  89613. }
  89614. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89615. continue;
  89616. }
  89617. currentPool.push(otherMesh);
  89618. globalLength--;
  89619. globalPool.splice(subIndex, 1);
  89620. subIndex--;
  89621. }
  89622. if (currentPool.length < 2) {
  89623. continue;
  89624. }
  89625. // Merge meshes
  89626. BABYLON.Mesh.MergeMeshes(currentPool);
  89627. }
  89628. if (updateSelectionTree != undefined) {
  89629. if (updateSelectionTree) {
  89630. scene.createOrUpdateSelectionOctree();
  89631. }
  89632. }
  89633. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89634. scene.createOrUpdateSelectionOctree();
  89635. }
  89636. return true;
  89637. };
  89638. ;
  89639. MergeMeshesOptimization._UpdateSelectionTree = false;
  89640. return MergeMeshesOptimization;
  89641. }(SceneOptimization));
  89642. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89643. /**
  89644. * Defines a list of options used by SceneOptimizer
  89645. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89646. */
  89647. var SceneOptimizerOptions = /** @class */ (function () {
  89648. /**
  89649. * Creates a new list of options used by SceneOptimizer
  89650. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89651. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89652. */
  89653. function SceneOptimizerOptions(
  89654. /**
  89655. * Defines the target frame rate to reach (60 by default)
  89656. */
  89657. targetFrameRate,
  89658. /**
  89659. * Defines the interval between two checkes (2000ms by default)
  89660. */
  89661. trackerDuration) {
  89662. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89663. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89664. this.targetFrameRate = targetFrameRate;
  89665. this.trackerDuration = trackerDuration;
  89666. /**
  89667. * Gets the list of optimizations to apply
  89668. */
  89669. this.optimizations = new Array();
  89670. }
  89671. /**
  89672. * Add a new optimization
  89673. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89674. * @returns the current SceneOptimizerOptions
  89675. */
  89676. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89677. this.optimizations.push(optimization);
  89678. return this;
  89679. };
  89680. /**
  89681. * Add a new custom optimization
  89682. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89683. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89684. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89685. * @returns the current SceneOptimizerOptions
  89686. */
  89687. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89688. if (priority === void 0) { priority = 0; }
  89689. var optimization = new CustomOptimization(priority);
  89690. optimization.onApply = onApply;
  89691. optimization.onGetDescription = onGetDescription;
  89692. this.optimizations.push(optimization);
  89693. return this;
  89694. };
  89695. /**
  89696. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89697. * @param targetFrameRate defines the target frame rate (60 by default)
  89698. * @returns a SceneOptimizerOptions object
  89699. */
  89700. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89701. var result = new SceneOptimizerOptions(targetFrameRate);
  89702. var priority = 0;
  89703. result.addOptimization(new MergeMeshesOptimization(priority));
  89704. result.addOptimization(new ShadowsOptimization(priority));
  89705. result.addOptimization(new LensFlaresOptimization(priority));
  89706. // Next priority
  89707. priority++;
  89708. result.addOptimization(new PostProcessesOptimization(priority));
  89709. result.addOptimization(new ParticlesOptimization(priority));
  89710. // Next priority
  89711. priority++;
  89712. result.addOptimization(new TextureOptimization(priority, 1024));
  89713. return result;
  89714. };
  89715. /**
  89716. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89717. * @param targetFrameRate defines the target frame rate (60 by default)
  89718. * @returns a SceneOptimizerOptions object
  89719. */
  89720. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89721. var result = new SceneOptimizerOptions(targetFrameRate);
  89722. var priority = 0;
  89723. result.addOptimization(new MergeMeshesOptimization(priority));
  89724. result.addOptimization(new ShadowsOptimization(priority));
  89725. result.addOptimization(new LensFlaresOptimization(priority));
  89726. // Next priority
  89727. priority++;
  89728. result.addOptimization(new PostProcessesOptimization(priority));
  89729. result.addOptimization(new ParticlesOptimization(priority));
  89730. // Next priority
  89731. priority++;
  89732. result.addOptimization(new TextureOptimization(priority, 512));
  89733. // Next priority
  89734. priority++;
  89735. result.addOptimization(new RenderTargetsOptimization(priority));
  89736. // Next priority
  89737. priority++;
  89738. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89739. return result;
  89740. };
  89741. /**
  89742. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89743. * @param targetFrameRate defines the target frame rate (60 by default)
  89744. * @returns a SceneOptimizerOptions object
  89745. */
  89746. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89747. var result = new SceneOptimizerOptions(targetFrameRate);
  89748. var priority = 0;
  89749. result.addOptimization(new MergeMeshesOptimization(priority));
  89750. result.addOptimization(new ShadowsOptimization(priority));
  89751. result.addOptimization(new LensFlaresOptimization(priority));
  89752. // Next priority
  89753. priority++;
  89754. result.addOptimization(new PostProcessesOptimization(priority));
  89755. result.addOptimization(new ParticlesOptimization(priority));
  89756. // Next priority
  89757. priority++;
  89758. result.addOptimization(new TextureOptimization(priority, 256));
  89759. // Next priority
  89760. priority++;
  89761. result.addOptimization(new RenderTargetsOptimization(priority));
  89762. // Next priority
  89763. priority++;
  89764. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89765. return result;
  89766. };
  89767. return SceneOptimizerOptions;
  89768. }());
  89769. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89770. /**
  89771. * Class used to run optimizations in order to reach a target frame rate
  89772. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89773. */
  89774. var SceneOptimizer = /** @class */ (function () {
  89775. /**
  89776. * Creates a new SceneOptimizer
  89777. * @param scene defines the scene to work on
  89778. * @param options defines the options to use with the SceneOptimizer
  89779. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89780. * @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)
  89781. */
  89782. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89783. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89784. if (improvementMode === void 0) { improvementMode = false; }
  89785. var _this = this;
  89786. this._isRunning = false;
  89787. this._currentPriorityLevel = 0;
  89788. this._targetFrameRate = 60;
  89789. this._trackerDuration = 2000;
  89790. this._currentFrameRate = 0;
  89791. this._improvementMode = false;
  89792. /**
  89793. * Defines an observable called when the optimizer reaches the target frame rate
  89794. */
  89795. this.onSuccessObservable = new BABYLON.Observable();
  89796. /**
  89797. * Defines an observable called when the optimizer enables an optimization
  89798. */
  89799. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89800. /**
  89801. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89802. */
  89803. this.onFailureObservable = new BABYLON.Observable();
  89804. if (!options) {
  89805. this._options = new SceneOptimizerOptions();
  89806. }
  89807. else {
  89808. this._options = options;
  89809. }
  89810. if (this._options.targetFrameRate) {
  89811. this._targetFrameRate = this._options.targetFrameRate;
  89812. }
  89813. if (this._options.trackerDuration) {
  89814. this._trackerDuration = this._options.trackerDuration;
  89815. }
  89816. if (autoGeneratePriorities) {
  89817. var priority = 0;
  89818. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89819. var optim = _a[_i];
  89820. optim.priority = priority++;
  89821. }
  89822. }
  89823. this._improvementMode = improvementMode;
  89824. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89825. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89826. _this._sceneDisposeObserver = null;
  89827. _this.dispose();
  89828. });
  89829. }
  89830. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89831. /**
  89832. * Gets a boolean indicating if the optimizer is in improvement mode
  89833. */
  89834. get: function () {
  89835. return this._improvementMode;
  89836. },
  89837. enumerable: true,
  89838. configurable: true
  89839. });
  89840. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89841. /**
  89842. * Gets the current priority level (0 at start)
  89843. */
  89844. get: function () {
  89845. return this._currentPriorityLevel;
  89846. },
  89847. enumerable: true,
  89848. configurable: true
  89849. });
  89850. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89851. /**
  89852. * Gets the current frame rate checked by the SceneOptimizer
  89853. */
  89854. get: function () {
  89855. return this._currentFrameRate;
  89856. },
  89857. enumerable: true,
  89858. configurable: true
  89859. });
  89860. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89861. /**
  89862. * Gets or sets the current target frame rate (60 by default)
  89863. */
  89864. get: function () {
  89865. return this._targetFrameRate;
  89866. },
  89867. /**
  89868. * Gets or sets the current target frame rate (60 by default)
  89869. */
  89870. set: function (value) {
  89871. this._targetFrameRate = value;
  89872. },
  89873. enumerable: true,
  89874. configurable: true
  89875. });
  89876. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89877. /**
  89878. * Gets or sets the current interval between two checks (every 2000ms by default)
  89879. */
  89880. get: function () {
  89881. return this._trackerDuration;
  89882. },
  89883. /**
  89884. * Gets or sets the current interval between two checks (every 2000ms by default)
  89885. */
  89886. set: function (value) {
  89887. this._trackerDuration = value;
  89888. },
  89889. enumerable: true,
  89890. configurable: true
  89891. });
  89892. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  89893. /**
  89894. * Gets the list of active optimizations
  89895. */
  89896. get: function () {
  89897. return this._options.optimizations;
  89898. },
  89899. enumerable: true,
  89900. configurable: true
  89901. });
  89902. /**
  89903. * Stops the current optimizer
  89904. */
  89905. SceneOptimizer.prototype.stop = function () {
  89906. this._isRunning = false;
  89907. };
  89908. /**
  89909. * Reset the optimizer to initial step (current priority level = 0)
  89910. */
  89911. SceneOptimizer.prototype.reset = function () {
  89912. this._currentPriorityLevel = 0;
  89913. };
  89914. /**
  89915. * Start the optimizer. By default it will try to reach a specific framerate
  89916. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89917. */
  89918. SceneOptimizer.prototype.start = function () {
  89919. var _this = this;
  89920. if (this._isRunning) {
  89921. return;
  89922. }
  89923. this._isRunning = true;
  89924. // Let's wait for the scene to be ready before running our check
  89925. this._scene.executeWhenReady(function () {
  89926. setTimeout(function () {
  89927. _this._checkCurrentState();
  89928. }, _this._trackerDuration);
  89929. });
  89930. };
  89931. SceneOptimizer.prototype._checkCurrentState = function () {
  89932. var _this = this;
  89933. if (!this._isRunning) {
  89934. return;
  89935. }
  89936. var scene = this._scene;
  89937. var options = this._options;
  89938. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89939. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89940. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89941. this._isRunning = false;
  89942. this.onSuccessObservable.notifyObservers(this);
  89943. return;
  89944. }
  89945. // Apply current level of optimizations
  89946. var allDone = true;
  89947. var noOptimizationApplied = true;
  89948. for (var index = 0; index < options.optimizations.length; index++) {
  89949. var optimization = options.optimizations[index];
  89950. if (optimization.priority === this._currentPriorityLevel) {
  89951. noOptimizationApplied = false;
  89952. allDone = allDone && optimization.apply(scene, this);
  89953. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89954. }
  89955. }
  89956. // If no optimization was applied, this is a failure :(
  89957. if (noOptimizationApplied) {
  89958. this._isRunning = false;
  89959. this.onFailureObservable.notifyObservers(this);
  89960. return;
  89961. }
  89962. // If all optimizations were done, move to next level
  89963. if (allDone) {
  89964. this._currentPriorityLevel++;
  89965. }
  89966. // Let's the system running for a specific amount of time before checking FPS
  89967. scene.executeWhenReady(function () {
  89968. setTimeout(function () {
  89969. _this._checkCurrentState();
  89970. }, _this._trackerDuration);
  89971. });
  89972. };
  89973. /**
  89974. * Release all resources
  89975. */
  89976. SceneOptimizer.prototype.dispose = function () {
  89977. this.stop();
  89978. this.onSuccessObservable.clear();
  89979. this.onFailureObservable.clear();
  89980. this.onNewOptimizationAppliedObservable.clear();
  89981. if (this._sceneDisposeObserver) {
  89982. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89983. }
  89984. };
  89985. /**
  89986. * Helper function to create a SceneOptimizer with one single line of code
  89987. * @param scene defines the scene to work on
  89988. * @param options defines the options to use with the SceneOptimizer
  89989. * @param onSuccess defines a callback to call on success
  89990. * @param onFailure defines a callback to call on failure
  89991. * @returns the new SceneOptimizer object
  89992. */
  89993. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89994. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89995. if (onSuccess) {
  89996. optimizer.onSuccessObservable.add(function () {
  89997. onSuccess();
  89998. });
  89999. }
  90000. if (onFailure) {
  90001. optimizer.onFailureObservable.add(function () {
  90002. onFailure();
  90003. });
  90004. }
  90005. optimizer.start();
  90006. return optimizer;
  90007. };
  90008. return SceneOptimizer;
  90009. }());
  90010. BABYLON.SceneOptimizer = SceneOptimizer;
  90011. })(BABYLON || (BABYLON = {}));
  90012. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90013. var BABYLON;
  90014. (function (BABYLON) {
  90015. var OutlineRenderer = /** @class */ (function () {
  90016. function OutlineRenderer(scene) {
  90017. this.zOffset = 1;
  90018. this._scene = scene;
  90019. }
  90020. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90021. var _this = this;
  90022. if (useOverlay === void 0) { useOverlay = false; }
  90023. var scene = this._scene;
  90024. var engine = this._scene.getEngine();
  90025. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90026. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90027. return;
  90028. }
  90029. var mesh = subMesh.getRenderingMesh();
  90030. var material = subMesh.getMaterial();
  90031. if (!material || !scene.activeCamera) {
  90032. return;
  90033. }
  90034. engine.enableEffect(this._effect);
  90035. // Logarithmic depth
  90036. if (material.useLogarithmicDepth) {
  90037. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90038. }
  90039. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90040. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90041. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90042. // Bones
  90043. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90044. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90045. }
  90046. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90047. // Alpha test
  90048. if (material && material.needAlphaTesting()) {
  90049. var alphaTexture = material.getAlphaTestTexture();
  90050. if (alphaTexture) {
  90051. this._effect.setTexture("diffuseSampler", alphaTexture);
  90052. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90053. }
  90054. }
  90055. engine.setZOffset(-this.zOffset);
  90056. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90057. engine.setZOffset(0);
  90058. };
  90059. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90060. var defines = [];
  90061. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90062. var mesh = subMesh.getMesh();
  90063. var material = subMesh.getMaterial();
  90064. if (material) {
  90065. // Alpha test
  90066. if (material.needAlphaTesting()) {
  90067. defines.push("#define ALPHATEST");
  90068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90069. attribs.push(BABYLON.VertexBuffer.UVKind);
  90070. defines.push("#define UV1");
  90071. }
  90072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90074. defines.push("#define UV2");
  90075. }
  90076. }
  90077. //Logarithmic depth
  90078. if (material.useLogarithmicDepth) {
  90079. defines.push("#define LOGARITHMICDEPTH");
  90080. }
  90081. }
  90082. // Bones
  90083. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90086. if (mesh.numBoneInfluencers > 4) {
  90087. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90088. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90089. }
  90090. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90091. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90092. }
  90093. else {
  90094. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90095. }
  90096. // Instances
  90097. if (useInstances) {
  90098. defines.push("#define INSTANCES");
  90099. attribs.push("world0");
  90100. attribs.push("world1");
  90101. attribs.push("world2");
  90102. attribs.push("world3");
  90103. }
  90104. // Get correct effect
  90105. var join = defines.join("\n");
  90106. if (this._cachedDefines !== join) {
  90107. this._cachedDefines = join;
  90108. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90109. }
  90110. return this._effect.isReady();
  90111. };
  90112. return OutlineRenderer;
  90113. }());
  90114. BABYLON.OutlineRenderer = OutlineRenderer;
  90115. })(BABYLON || (BABYLON = {}));
  90116. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90117. var BABYLON;
  90118. (function (BABYLON) {
  90119. var FaceAdjacencies = /** @class */ (function () {
  90120. function FaceAdjacencies() {
  90121. this.edges = new Array();
  90122. this.edgesConnectedCount = 0;
  90123. }
  90124. return FaceAdjacencies;
  90125. }());
  90126. var EdgesRenderer = /** @class */ (function () {
  90127. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90128. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90129. if (epsilon === void 0) { epsilon = 0.95; }
  90130. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90131. this.edgesWidthScalerForOrthographic = 1000.0;
  90132. this.edgesWidthScalerForPerspective = 50.0;
  90133. this._linesPositions = new Array();
  90134. this._linesNormals = new Array();
  90135. this._linesIndices = new Array();
  90136. this._buffers = {};
  90137. this._checkVerticesInsteadOfIndices = false;
  90138. this._source = source;
  90139. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90140. this._epsilon = epsilon;
  90141. this._prepareRessources();
  90142. this._generateEdgesLines();
  90143. }
  90144. EdgesRenderer.prototype._prepareRessources = function () {
  90145. if (this._lineShader) {
  90146. return;
  90147. }
  90148. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90149. attributes: ["position", "normal"],
  90150. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90151. });
  90152. this._lineShader.disableDepthWrite = true;
  90153. this._lineShader.backFaceCulling = false;
  90154. };
  90155. EdgesRenderer.prototype._rebuild = function () {
  90156. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90157. if (buffer) {
  90158. buffer._rebuild();
  90159. }
  90160. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90161. if (buffer) {
  90162. buffer._rebuild();
  90163. }
  90164. var scene = this._source.getScene();
  90165. var engine = scene.getEngine();
  90166. this._ib = engine.createIndexBuffer(this._linesIndices);
  90167. };
  90168. EdgesRenderer.prototype.dispose = function () {
  90169. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90170. if (buffer) {
  90171. buffer.dispose();
  90172. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90173. }
  90174. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90175. if (buffer) {
  90176. buffer.dispose();
  90177. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90178. }
  90179. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90180. this._lineShader.dispose();
  90181. };
  90182. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90183. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90184. return 0;
  90185. }
  90186. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90187. return 1;
  90188. }
  90189. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90190. return 2;
  90191. }
  90192. return -1;
  90193. };
  90194. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90195. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90196. return 0;
  90197. }
  90198. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90199. return 1;
  90200. }
  90201. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90202. return 2;
  90203. }
  90204. return -1;
  90205. };
  90206. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90207. var needToCreateLine;
  90208. if (edge === undefined) {
  90209. needToCreateLine = true;
  90210. }
  90211. else {
  90212. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90213. needToCreateLine = dotProduct < this._epsilon;
  90214. }
  90215. if (needToCreateLine) {
  90216. var offset = this._linesPositions.length / 3;
  90217. var normal = p0.subtract(p1);
  90218. normal.normalize();
  90219. // Positions
  90220. this._linesPositions.push(p0.x);
  90221. this._linesPositions.push(p0.y);
  90222. this._linesPositions.push(p0.z);
  90223. this._linesPositions.push(p0.x);
  90224. this._linesPositions.push(p0.y);
  90225. this._linesPositions.push(p0.z);
  90226. this._linesPositions.push(p1.x);
  90227. this._linesPositions.push(p1.y);
  90228. this._linesPositions.push(p1.z);
  90229. this._linesPositions.push(p1.x);
  90230. this._linesPositions.push(p1.y);
  90231. this._linesPositions.push(p1.z);
  90232. // Normals
  90233. this._linesNormals.push(p1.x);
  90234. this._linesNormals.push(p1.y);
  90235. this._linesNormals.push(p1.z);
  90236. this._linesNormals.push(-1);
  90237. this._linesNormals.push(p1.x);
  90238. this._linesNormals.push(p1.y);
  90239. this._linesNormals.push(p1.z);
  90240. this._linesNormals.push(1);
  90241. this._linesNormals.push(p0.x);
  90242. this._linesNormals.push(p0.y);
  90243. this._linesNormals.push(p0.z);
  90244. this._linesNormals.push(-1);
  90245. this._linesNormals.push(p0.x);
  90246. this._linesNormals.push(p0.y);
  90247. this._linesNormals.push(p0.z);
  90248. this._linesNormals.push(1);
  90249. // Indices
  90250. this._linesIndices.push(offset);
  90251. this._linesIndices.push(offset + 1);
  90252. this._linesIndices.push(offset + 2);
  90253. this._linesIndices.push(offset);
  90254. this._linesIndices.push(offset + 2);
  90255. this._linesIndices.push(offset + 3);
  90256. }
  90257. };
  90258. EdgesRenderer.prototype._generateEdgesLines = function () {
  90259. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90260. var indices = this._source.getIndices();
  90261. if (!indices || !positions) {
  90262. return;
  90263. }
  90264. // First let's find adjacencies
  90265. var adjacencies = new Array();
  90266. var faceNormals = new Array();
  90267. var index;
  90268. var faceAdjacencies;
  90269. // Prepare faces
  90270. for (index = 0; index < indices.length; index += 3) {
  90271. faceAdjacencies = new FaceAdjacencies();
  90272. var p0Index = indices[index];
  90273. var p1Index = indices[index + 1];
  90274. var p2Index = indices[index + 2];
  90275. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90276. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90277. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90278. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90279. faceNormal.normalize();
  90280. faceNormals.push(faceNormal);
  90281. adjacencies.push(faceAdjacencies);
  90282. }
  90283. // Scan
  90284. for (index = 0; index < adjacencies.length; index++) {
  90285. faceAdjacencies = adjacencies[index];
  90286. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90287. var otherFaceAdjacencies = adjacencies[otherIndex];
  90288. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90289. break;
  90290. }
  90291. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90292. continue;
  90293. }
  90294. var otherP0 = indices[otherIndex * 3];
  90295. var otherP1 = indices[otherIndex * 3 + 1];
  90296. var otherP2 = indices[otherIndex * 3 + 2];
  90297. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90298. var otherEdgeIndex = 0;
  90299. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90300. continue;
  90301. }
  90302. switch (edgeIndex) {
  90303. case 0:
  90304. if (this._checkVerticesInsteadOfIndices) {
  90305. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90306. }
  90307. else {
  90308. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90309. }
  90310. break;
  90311. case 1:
  90312. if (this._checkVerticesInsteadOfIndices) {
  90313. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90314. }
  90315. else {
  90316. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90317. }
  90318. break;
  90319. case 2:
  90320. if (this._checkVerticesInsteadOfIndices) {
  90321. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90322. }
  90323. else {
  90324. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90325. }
  90326. break;
  90327. }
  90328. if (otherEdgeIndex === -1) {
  90329. continue;
  90330. }
  90331. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90332. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90333. faceAdjacencies.edgesConnectedCount++;
  90334. otherFaceAdjacencies.edgesConnectedCount++;
  90335. if (faceAdjacencies.edgesConnectedCount === 3) {
  90336. break;
  90337. }
  90338. }
  90339. }
  90340. }
  90341. // Create lines
  90342. for (index = 0; index < adjacencies.length; index++) {
  90343. // 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
  90344. var current = adjacencies[index];
  90345. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90346. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90347. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90348. }
  90349. // Merge into a single mesh
  90350. var engine = this._source.getScene().getEngine();
  90351. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90352. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90353. this._ib = engine.createIndexBuffer(this._linesIndices);
  90354. this._indicesCount = this._linesIndices.length;
  90355. };
  90356. EdgesRenderer.prototype.render = function () {
  90357. var scene = this._source.getScene();
  90358. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90359. return;
  90360. }
  90361. var engine = scene.getEngine();
  90362. this._lineShader._preBind();
  90363. // VBOs
  90364. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90365. scene.resetCachedMaterial();
  90366. this._lineShader.setColor4("color", this._source.edgesColor);
  90367. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90368. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90369. }
  90370. else {
  90371. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90372. }
  90373. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  90374. this._lineShader.bind(this._source.getWorldMatrix());
  90375. // Draw order
  90376. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  90377. this._lineShader.unbind();
  90378. engine.setDepthWrite(true);
  90379. };
  90380. return EdgesRenderer;
  90381. }());
  90382. BABYLON.EdgesRenderer = EdgesRenderer;
  90383. })(BABYLON || (BABYLON = {}));
  90384. //# sourceMappingURL=babylon.edgesRenderer.js.map
  90385. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90386. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90387. s = arguments[i];
  90388. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90389. t[p] = s[p];
  90390. }
  90391. return t;
  90392. };
  90393. var BABYLON;
  90394. (function (BABYLON) {
  90395. /**
  90396. * The effect layer Helps adding post process effect blended with the main pass.
  90397. *
  90398. * This can be for instance use to generate glow or higlight effects on the scene.
  90399. *
  90400. * The effect layer class can not be used directly and is intented to inherited from to be
  90401. * customized per effects.
  90402. */
  90403. var EffectLayer = /** @class */ (function () {
  90404. /**
  90405. * Instantiates a new effect Layer and references it in the scene.
  90406. * @param name The name of the layer
  90407. * @param scene The scene to use the layer in
  90408. */
  90409. function EffectLayer(
  90410. /** The Friendly of the effect in the scene */
  90411. name, scene) {
  90412. this._vertexBuffers = {};
  90413. this._maxSize = 0;
  90414. this._mainTextureDesiredSize = { width: 0, height: 0 };
  90415. this._shouldRender = true;
  90416. this._postProcesses = [];
  90417. this._textures = [];
  90418. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  90419. /**
  90420. * The clear color of the texture used to generate the glow map.
  90421. */
  90422. this.neutralColor = new BABYLON.Color4();
  90423. /**
  90424. * Specifies wether the highlight layer is enabled or not.
  90425. */
  90426. this.isEnabled = true;
  90427. /**
  90428. * An event triggered when the effect layer has been disposed.
  90429. */
  90430. this.onDisposeObservable = new BABYLON.Observable();
  90431. /**
  90432. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  90433. */
  90434. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  90435. /**
  90436. * An event triggered when the generated texture is being merged in the scene.
  90437. */
  90438. this.onBeforeComposeObservable = new BABYLON.Observable();
  90439. /**
  90440. * An event triggered when the generated texture has been merged in the scene.
  90441. */
  90442. this.onAfterComposeObservable = new BABYLON.Observable();
  90443. /**
  90444. * An event triggered when the efffect layer changes its size.
  90445. */
  90446. this.onSizeChangedObservable = new BABYLON.Observable();
  90447. this.name = name;
  90448. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90449. this._engine = scene.getEngine();
  90450. this._maxSize = this._engine.getCaps().maxTextureSize;
  90451. this._scene.effectLayers.push(this);
  90452. // Generate Buffers
  90453. this._generateIndexBuffer();
  90454. this._genrateVertexBuffer();
  90455. }
  90456. Object.defineProperty(EffectLayer.prototype, "camera", {
  90457. /**
  90458. * Gets the camera attached to the layer.
  90459. */
  90460. get: function () {
  90461. return this._effectLayerOptions.camera;
  90462. },
  90463. enumerable: true,
  90464. configurable: true
  90465. });
  90466. /**
  90467. * Initializes the effect layer with the required options.
  90468. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  90469. */
  90470. EffectLayer.prototype._init = function (options) {
  90471. // Adapt options
  90472. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90473. this._setMainTextureSize();
  90474. this._createMainTexture();
  90475. this._createTextureAndPostProcesses();
  90476. this._mergeEffect = this._createMergeEffect();
  90477. };
  90478. /**
  90479. * Generates the index buffer of the full screen quad blending to the main canvas.
  90480. */
  90481. EffectLayer.prototype._generateIndexBuffer = function () {
  90482. // Indices
  90483. var indices = [];
  90484. indices.push(0);
  90485. indices.push(1);
  90486. indices.push(2);
  90487. indices.push(0);
  90488. indices.push(2);
  90489. indices.push(3);
  90490. this._indexBuffer = this._engine.createIndexBuffer(indices);
  90491. };
  90492. /**
  90493. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  90494. */
  90495. EffectLayer.prototype._genrateVertexBuffer = function () {
  90496. // VBO
  90497. var vertices = [];
  90498. vertices.push(1, 1);
  90499. vertices.push(-1, 1);
  90500. vertices.push(-1, -1);
  90501. vertices.push(1, -1);
  90502. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90503. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  90504. };
  90505. /**
  90506. * Sets the main texture desired size which is the closest power of two
  90507. * of the engine canvas size.
  90508. */
  90509. EffectLayer.prototype._setMainTextureSize = function () {
  90510. if (this._effectLayerOptions.mainTextureFixedSize) {
  90511. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  90512. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  90513. }
  90514. else {
  90515. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  90516. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  90517. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  90518. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  90519. }
  90520. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  90521. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  90522. };
  90523. /**
  90524. * Creates the main texture for the effect layer.
  90525. */
  90526. EffectLayer.prototype._createMainTexture = function () {
  90527. var _this = this;
  90528. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  90529. width: this._mainTextureDesiredSize.width,
  90530. height: this._mainTextureDesiredSize.height
  90531. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90532. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  90533. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90534. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90535. this._mainTexture.anisotropicFilteringLevel = 1;
  90536. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90537. this._mainTexture.renderParticles = false;
  90538. this._mainTexture.renderList = null;
  90539. this._mainTexture.ignoreCameraViewport = true;
  90540. // Custom render function
  90541. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90542. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  90543. var index;
  90544. var engine = _this._scene.getEngine();
  90545. if (depthOnlySubMeshes.length) {
  90546. engine.setColorWrite(false);
  90547. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90548. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  90549. }
  90550. engine.setColorWrite(true);
  90551. }
  90552. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90553. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  90554. }
  90555. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90556. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  90557. }
  90558. for (index = 0; index < transparentSubMeshes.length; index++) {
  90559. _this._renderSubMesh(transparentSubMeshes.data[index]);
  90560. }
  90561. };
  90562. this._mainTexture.onClearObservable.add(function (engine) {
  90563. engine.clear(_this.neutralColor, true, true, true);
  90564. });
  90565. };
  90566. /**
  90567. * Checks for the readiness of the element composing the layer.
  90568. * @param subMesh the mesh to check for
  90569. * @param useInstances specify wether or not to use instances to render the mesh
  90570. * @param emissiveTexture the associated emissive texture used to generate the glow
  90571. * @return true if ready otherwise, false
  90572. */
  90573. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  90574. var material = subMesh.getMaterial();
  90575. if (!material) {
  90576. return false;
  90577. }
  90578. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  90579. return false;
  90580. }
  90581. var defines = [];
  90582. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90583. var mesh = subMesh.getMesh();
  90584. var uv1 = false;
  90585. var uv2 = false;
  90586. // Alpha test
  90587. if (material && material.needAlphaTesting()) {
  90588. var alphaTexture = material.getAlphaTestTexture();
  90589. if (alphaTexture) {
  90590. defines.push("#define ALPHATEST");
  90591. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90592. alphaTexture.coordinatesIndex === 1) {
  90593. defines.push("#define DIFFUSEUV2");
  90594. uv2 = true;
  90595. }
  90596. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90597. defines.push("#define DIFFUSEUV1");
  90598. uv1 = true;
  90599. }
  90600. }
  90601. }
  90602. // Emissive
  90603. if (emissiveTexture) {
  90604. defines.push("#define EMISSIVE");
  90605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90606. emissiveTexture.coordinatesIndex === 1) {
  90607. defines.push("#define EMISSIVEUV2");
  90608. uv2 = true;
  90609. }
  90610. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90611. defines.push("#define EMISSIVEUV1");
  90612. uv1 = true;
  90613. }
  90614. }
  90615. if (uv1) {
  90616. attribs.push(BABYLON.VertexBuffer.UVKind);
  90617. defines.push("#define UV1");
  90618. }
  90619. if (uv2) {
  90620. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90621. defines.push("#define UV2");
  90622. }
  90623. // Bones
  90624. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90625. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90626. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90627. if (mesh.numBoneInfluencers > 4) {
  90628. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90629. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90630. }
  90631. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90632. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90633. }
  90634. else {
  90635. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90636. }
  90637. // Morph targets
  90638. var manager = mesh.morphTargetManager;
  90639. var morphInfluencers = 0;
  90640. if (manager) {
  90641. if (manager.numInfluencers > 0) {
  90642. defines.push("#define MORPHTARGETS");
  90643. morphInfluencers = manager.numInfluencers;
  90644. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90645. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90646. }
  90647. }
  90648. // Instances
  90649. if (useInstances) {
  90650. defines.push("#define INSTANCES");
  90651. attribs.push("world0");
  90652. attribs.push("world1");
  90653. attribs.push("world2");
  90654. attribs.push("world3");
  90655. }
  90656. // Get correct effect
  90657. var join = defines.join("\n");
  90658. if (this._cachedDefines !== join) {
  90659. this._cachedDefines = join;
  90660. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90661. }
  90662. return this._effectLayerMapGenerationEffect.isReady();
  90663. };
  90664. /**
  90665. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90666. */
  90667. EffectLayer.prototype.render = function () {
  90668. var currentEffect = this._mergeEffect;
  90669. // Check
  90670. if (!currentEffect.isReady())
  90671. return;
  90672. for (var i = 0; i < this._postProcesses.length; i++) {
  90673. if (!this._postProcesses[i].isReady()) {
  90674. return;
  90675. }
  90676. }
  90677. var engine = this._scene.getEngine();
  90678. this.onBeforeComposeObservable.notifyObservers(this);
  90679. // Render
  90680. engine.enableEffect(currentEffect);
  90681. engine.setState(false);
  90682. // VBOs
  90683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90684. // Cache
  90685. var previousAlphaMode = engine.getAlphaMode();
  90686. // Go Blend.
  90687. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90688. // Blends the map on the main canvas.
  90689. this._internalRender(currentEffect);
  90690. // Restore Alpha
  90691. engine.setAlphaMode(previousAlphaMode);
  90692. this.onAfterComposeObservable.notifyObservers(this);
  90693. // Handle size changes.
  90694. var size = this._mainTexture.getSize();
  90695. this._setMainTextureSize();
  90696. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90697. // Recreate RTT and post processes on size change.
  90698. this.onSizeChangedObservable.notifyObservers(this);
  90699. this._disposeTextureAndPostProcesses();
  90700. this._createMainTexture();
  90701. this._createTextureAndPostProcesses();
  90702. }
  90703. };
  90704. /**
  90705. * Determine if a given mesh will be used in the current effect.
  90706. * @param mesh mesh to test
  90707. * @returns true if the mesh will be used
  90708. */
  90709. EffectLayer.prototype.hasMesh = function (mesh) {
  90710. return true;
  90711. };
  90712. /**
  90713. * Returns true if the layer contains information to display, otherwise false.
  90714. * @returns true if the glow layer should be rendered
  90715. */
  90716. EffectLayer.prototype.shouldRender = function () {
  90717. return this.isEnabled && this._shouldRender;
  90718. };
  90719. /**
  90720. * Returns true if the mesh should render, otherwise false.
  90721. * @param mesh The mesh to render
  90722. * @returns true if it should render otherwise false
  90723. */
  90724. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90725. return true;
  90726. };
  90727. /**
  90728. * Returns true if the mesh should render, otherwise false.
  90729. * @param mesh The mesh to render
  90730. * @returns true if it should render otherwise false
  90731. */
  90732. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90733. return true;
  90734. };
  90735. /**
  90736. * Renders the submesh passed in parameter to the generation map.
  90737. */
  90738. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90739. var _this = this;
  90740. if (!this.shouldRender()) {
  90741. return;
  90742. }
  90743. var material = subMesh.getMaterial();
  90744. var mesh = subMesh.getRenderingMesh();
  90745. var scene = this._scene;
  90746. var engine = scene.getEngine();
  90747. if (!material) {
  90748. return;
  90749. }
  90750. // Do not block in blend mode.
  90751. if (material.needAlphaBlendingForMesh(mesh)) {
  90752. return;
  90753. }
  90754. // Culling
  90755. engine.setState(material.backFaceCulling);
  90756. // Managing instances
  90757. var batch = mesh._getInstancesRenderList(subMesh._id);
  90758. if (batch.mustReturn) {
  90759. return;
  90760. }
  90761. // Early Exit per mesh
  90762. if (!this._shouldRenderMesh(mesh)) {
  90763. return;
  90764. }
  90765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90766. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90767. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90768. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90769. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90770. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90771. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90772. // Alpha test
  90773. if (material && material.needAlphaTesting()) {
  90774. var alphaTexture = material.getAlphaTestTexture();
  90775. if (alphaTexture) {
  90776. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90777. var textureMatrix = alphaTexture.getTextureMatrix();
  90778. if (textureMatrix) {
  90779. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90780. }
  90781. }
  90782. }
  90783. // Glow emissive only
  90784. if (this._emissiveTextureAndColor.texture) {
  90785. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90786. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90787. }
  90788. // Bones
  90789. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90790. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90791. }
  90792. // Morph targets
  90793. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90794. // Draw
  90795. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90796. }
  90797. else {
  90798. // Need to reset refresh rate of the shadowMap
  90799. this._mainTexture.resetRefreshCounter();
  90800. }
  90801. };
  90802. /**
  90803. * Rebuild the required buffers.
  90804. * @ignore Internal use only.
  90805. */
  90806. EffectLayer.prototype._rebuild = function () {
  90807. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90808. if (vb) {
  90809. vb._rebuild();
  90810. }
  90811. this._generateIndexBuffer();
  90812. };
  90813. /**
  90814. * Dispose only the render target textures and post process.
  90815. */
  90816. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90817. this._mainTexture.dispose();
  90818. for (var i = 0; i < this._postProcesses.length; i++) {
  90819. if (this._postProcesses[i]) {
  90820. this._postProcesses[i].dispose();
  90821. }
  90822. }
  90823. this._postProcesses = [];
  90824. for (var i = 0; i < this._textures.length; i++) {
  90825. if (this._textures[i]) {
  90826. this._textures[i].dispose();
  90827. }
  90828. }
  90829. this._textures = [];
  90830. };
  90831. /**
  90832. * Dispose the highlight layer and free resources.
  90833. */
  90834. EffectLayer.prototype.dispose = function () {
  90835. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90836. if (vertexBuffer) {
  90837. vertexBuffer.dispose();
  90838. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90839. }
  90840. if (this._indexBuffer) {
  90841. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90842. this._indexBuffer = null;
  90843. }
  90844. // Clean textures and post processes
  90845. this._disposeTextureAndPostProcesses();
  90846. // Remove from scene
  90847. var index = this._scene.effectLayers.indexOf(this, 0);
  90848. if (index > -1) {
  90849. this._scene.effectLayers.splice(index, 1);
  90850. }
  90851. // Callback
  90852. this.onDisposeObservable.notifyObservers(this);
  90853. this.onDisposeObservable.clear();
  90854. this.onBeforeRenderMainTextureObservable.clear();
  90855. this.onBeforeComposeObservable.clear();
  90856. this.onAfterComposeObservable.clear();
  90857. this.onSizeChangedObservable.clear();
  90858. };
  90859. /**
  90860. * Gets the class name of the effect layer
  90861. * @returns the string with the class name of the effect layer
  90862. */
  90863. EffectLayer.prototype.getClassName = function () {
  90864. return "EffectLayer";
  90865. };
  90866. /**
  90867. * Creates an effect layer from parsed effect layer data
  90868. * @param parsedEffectLayer defines effect layer data
  90869. * @param scene defines the current scene
  90870. * @param rootUrl defines the root URL containing the effect layer information
  90871. * @returns a parsed effect Layer
  90872. */
  90873. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90874. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90875. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90876. };
  90877. __decorate([
  90878. BABYLON.serialize()
  90879. ], EffectLayer.prototype, "name", void 0);
  90880. __decorate([
  90881. BABYLON.serializeAsColor4()
  90882. ], EffectLayer.prototype, "neutralColor", void 0);
  90883. __decorate([
  90884. BABYLON.serialize()
  90885. ], EffectLayer.prototype, "isEnabled", void 0);
  90886. __decorate([
  90887. BABYLON.serializeAsCameraReference()
  90888. ], EffectLayer.prototype, "camera", null);
  90889. return EffectLayer;
  90890. }());
  90891. BABYLON.EffectLayer = EffectLayer;
  90892. })(BABYLON || (BABYLON = {}));
  90893. //# sourceMappingURL=babylon.effectLayer.js.map
  90894. var BABYLON;
  90895. (function (BABYLON) {
  90896. /**
  90897. * Special Glow Blur post process only blurring the alpha channel
  90898. * It enforces keeping the most luminous color in the color channel.
  90899. */
  90900. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90901. __extends(GlowBlurPostProcess, _super);
  90902. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90904. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90905. _this.direction = direction;
  90906. _this.kernel = kernel;
  90907. _this.onApplyObservable.add(function (effect) {
  90908. effect.setFloat2("screenSize", _this.width, _this.height);
  90909. effect.setVector2("direction", _this.direction);
  90910. effect.setFloat("blurWidth", _this.kernel);
  90911. });
  90912. return _this;
  90913. }
  90914. return GlowBlurPostProcess;
  90915. }(BABYLON.PostProcess));
  90916. /**
  90917. * The highlight layer Helps adding a glow effect around a mesh.
  90918. *
  90919. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90920. * glowy meshes to your scene.
  90921. *
  90922. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90923. */
  90924. var HighlightLayer = /** @class */ (function (_super) {
  90925. __extends(HighlightLayer, _super);
  90926. /**
  90927. * Instantiates a new highlight Layer and references it to the scene..
  90928. * @param name The name of the layer
  90929. * @param scene The scene to use the layer in
  90930. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90931. */
  90932. function HighlightLayer(name, scene, options) {
  90933. var _this = _super.call(this, name, scene) || this;
  90934. _this.name = name;
  90935. /**
  90936. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90937. */
  90938. _this.innerGlow = true;
  90939. /**
  90940. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90941. */
  90942. _this.outerGlow = true;
  90943. /**
  90944. * An event triggered when the highlight layer is being blurred.
  90945. */
  90946. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90947. /**
  90948. * An event triggered when the highlight layer has been blurred.
  90949. */
  90950. _this.onAfterBlurObservable = new BABYLON.Observable();
  90951. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90952. _this._meshes = {};
  90953. _this._excludedMeshes = {};
  90954. _this.neutralColor = HighlightLayer.NeutralColor;
  90955. // Warn on stencil
  90956. if (!_this._engine.isStencilEnable) {
  90957. 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 }");
  90958. }
  90959. // Adapt options
  90960. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90961. // Initialize the layer
  90962. _this._init({
  90963. alphaBlendingMode: _this._options.alphaBlendingMode,
  90964. camera: _this._options.camera,
  90965. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90966. mainTextureRatio: _this._options.mainTextureRatio
  90967. });
  90968. // Do not render as long as no meshes have been added
  90969. _this._shouldRender = false;
  90970. return _this;
  90971. }
  90972. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90973. /**
  90974. * Gets the horizontal size of the blur.
  90975. */
  90976. get: function () {
  90977. return this._horizontalBlurPostprocess.kernel;
  90978. },
  90979. /**
  90980. * Specifies the horizontal size of the blur.
  90981. */
  90982. set: function (value) {
  90983. this._horizontalBlurPostprocess.kernel = value;
  90984. },
  90985. enumerable: true,
  90986. configurable: true
  90987. });
  90988. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90989. /**
  90990. * Gets the vertical size of the blur.
  90991. */
  90992. get: function () {
  90993. return this._verticalBlurPostprocess.kernel;
  90994. },
  90995. /**
  90996. * Specifies the vertical size of the blur.
  90997. */
  90998. set: function (value) {
  90999. this._verticalBlurPostprocess.kernel = value;
  91000. },
  91001. enumerable: true,
  91002. configurable: true
  91003. });
  91004. /**
  91005. * Get the effect name of the layer.
  91006. * @return The effect name
  91007. */
  91008. HighlightLayer.prototype.getEffectName = function () {
  91009. return HighlightLayer.EffectName;
  91010. };
  91011. /**
  91012. * Create the merge effect. This is the shader use to blit the information back
  91013. * to the main canvas at the end of the scene rendering.
  91014. */
  91015. HighlightLayer.prototype._createMergeEffect = function () {
  91016. // Effect
  91017. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91018. };
  91019. /**
  91020. * Creates the render target textures and post processes used in the highlight layer.
  91021. */
  91022. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91023. var _this = this;
  91024. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91025. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91026. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91027. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91028. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91029. width: blurTextureWidth,
  91030. height: blurTextureHeight
  91031. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91032. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91033. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91034. this._blurTexture.anisotropicFilteringLevel = 16;
  91035. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91036. this._blurTexture.renderParticles = false;
  91037. this._blurTexture.ignoreCameraViewport = true;
  91038. this._textures = [this._blurTexture];
  91039. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91040. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91041. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91042. effect.setTexture("textureSampler", _this._mainTexture);
  91043. });
  91044. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91045. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91046. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91047. });
  91048. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91049. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91050. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91051. });
  91052. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91053. }
  91054. else {
  91055. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91056. width: blurTextureWidth,
  91057. height: blurTextureHeight
  91058. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91059. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91060. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91061. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91062. effect.setTexture("textureSampler", _this._mainTexture);
  91063. });
  91064. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91065. width: blurTextureWidth,
  91066. height: blurTextureHeight
  91067. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91068. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91069. }
  91070. this._mainTexture.onAfterUnbindObservable.add(function () {
  91071. _this.onBeforeBlurObservable.notifyObservers(_this);
  91072. var internalTexture = _this._blurTexture.getInternalTexture();
  91073. if (internalTexture) {
  91074. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91075. }
  91076. _this.onAfterBlurObservable.notifyObservers(_this);
  91077. });
  91078. // Prevent autoClear.
  91079. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91080. };
  91081. /**
  91082. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91083. */
  91084. HighlightLayer.prototype.needStencil = function () {
  91085. return true;
  91086. };
  91087. /**
  91088. * Checks for the readiness of the element composing the layer.
  91089. * @param subMesh the mesh to check for
  91090. * @param useInstances specify wether or not to use instances to render the mesh
  91091. * @param emissiveTexture the associated emissive texture used to generate the glow
  91092. * @return true if ready otherwise, false
  91093. */
  91094. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91095. var material = subMesh.getMaterial();
  91096. var mesh = subMesh.getRenderingMesh();
  91097. if (!material || !mesh || !this._meshes) {
  91098. return false;
  91099. }
  91100. var emissiveTexture = null;
  91101. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91102. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91103. emissiveTexture = material.emissiveTexture;
  91104. }
  91105. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91106. };
  91107. /**
  91108. * Implementation specific of rendering the generating effect on the main canvas.
  91109. * @param effect The effect used to render through
  91110. */
  91111. HighlightLayer.prototype._internalRender = function (effect) {
  91112. // Texture
  91113. effect.setTexture("textureSampler", this._blurTexture);
  91114. // Cache
  91115. var engine = this._engine;
  91116. var previousStencilBuffer = engine.getStencilBuffer();
  91117. var previousStencilFunction = engine.getStencilFunction();
  91118. var previousStencilMask = engine.getStencilMask();
  91119. var previousStencilOperationPass = engine.getStencilOperationPass();
  91120. var previousStencilOperationFail = engine.getStencilOperationFail();
  91121. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91122. var previousStencilReference = engine.getStencilFunctionReference();
  91123. // Stencil operations
  91124. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91125. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91126. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91127. // Draw order
  91128. engine.setStencilMask(0x00);
  91129. engine.setStencilBuffer(true);
  91130. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91131. // 2 passes inner outer
  91132. if (this.outerGlow) {
  91133. effect.setFloat("offset", 0);
  91134. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91135. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91136. }
  91137. if (this.innerGlow) {
  91138. effect.setFloat("offset", 1);
  91139. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91140. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91141. }
  91142. // Restore Cache
  91143. engine.setStencilFunction(previousStencilFunction);
  91144. engine.setStencilMask(previousStencilMask);
  91145. engine.setStencilBuffer(previousStencilBuffer);
  91146. engine.setStencilOperationPass(previousStencilOperationPass);
  91147. engine.setStencilOperationFail(previousStencilOperationFail);
  91148. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91149. engine.setStencilFunctionReference(previousStencilReference);
  91150. };
  91151. /**
  91152. * Returns true if the layer contains information to display, otherwise false.
  91153. */
  91154. HighlightLayer.prototype.shouldRender = function () {
  91155. if (_super.prototype.shouldRender.call(this)) {
  91156. return this._meshes ? true : false;
  91157. }
  91158. return false;
  91159. };
  91160. /**
  91161. * Returns true if the mesh should render, otherwise false.
  91162. * @param mesh The mesh to render
  91163. * @returns true if it should render otherwise false
  91164. */
  91165. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91166. // Excluded Mesh
  91167. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91168. return false;
  91169. }
  91170. ;
  91171. return true;
  91172. };
  91173. /**
  91174. * Sets the required values for both the emissive texture and and the main color.
  91175. */
  91176. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91177. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91178. if (highlightLayerMesh) {
  91179. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91180. }
  91181. else {
  91182. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91183. }
  91184. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91185. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91186. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91187. }
  91188. else {
  91189. this._emissiveTextureAndColor.texture = null;
  91190. }
  91191. };
  91192. /**
  91193. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91194. * @param mesh The mesh to exclude from the highlight layer
  91195. */
  91196. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91197. if (!this._excludedMeshes) {
  91198. return;
  91199. }
  91200. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91201. if (!meshExcluded) {
  91202. this._excludedMeshes[mesh.uniqueId] = {
  91203. mesh: mesh,
  91204. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91205. mesh.getEngine().setStencilBuffer(false);
  91206. }),
  91207. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91208. mesh.getEngine().setStencilBuffer(true);
  91209. }),
  91210. };
  91211. }
  91212. };
  91213. /**
  91214. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91215. * @param mesh The mesh to highlight
  91216. */
  91217. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91218. if (!this._excludedMeshes) {
  91219. return;
  91220. }
  91221. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91222. if (meshExcluded) {
  91223. if (meshExcluded.beforeRender) {
  91224. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91225. }
  91226. if (meshExcluded.afterRender) {
  91227. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91228. }
  91229. }
  91230. this._excludedMeshes[mesh.uniqueId] = null;
  91231. };
  91232. /**
  91233. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91234. * @param mesh mesh to test
  91235. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91236. */
  91237. HighlightLayer.prototype.hasMesh = function (mesh) {
  91238. if (!this._meshes) {
  91239. return false;
  91240. }
  91241. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91242. };
  91243. /**
  91244. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91245. * @param mesh The mesh to highlight
  91246. * @param color The color of the highlight
  91247. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91248. */
  91249. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91250. var _this = this;
  91251. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91252. if (!this._meshes) {
  91253. return;
  91254. }
  91255. var meshHighlight = this._meshes[mesh.uniqueId];
  91256. if (meshHighlight) {
  91257. meshHighlight.color = color;
  91258. }
  91259. else {
  91260. this._meshes[mesh.uniqueId] = {
  91261. mesh: mesh,
  91262. color: color,
  91263. // Lambda required for capture due to Observable this context
  91264. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91265. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91266. _this._defaultStencilReference(mesh);
  91267. }
  91268. else {
  91269. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91270. }
  91271. }),
  91272. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91273. glowEmissiveOnly: glowEmissiveOnly
  91274. };
  91275. }
  91276. this._shouldRender = true;
  91277. };
  91278. /**
  91279. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91280. * @param mesh The mesh to highlight
  91281. */
  91282. HighlightLayer.prototype.removeMesh = function (mesh) {
  91283. if (!this._meshes) {
  91284. return;
  91285. }
  91286. var meshHighlight = this._meshes[mesh.uniqueId];
  91287. if (meshHighlight) {
  91288. if (meshHighlight.observerHighlight) {
  91289. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91290. }
  91291. if (meshHighlight.observerDefault) {
  91292. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91293. }
  91294. delete this._meshes[mesh.uniqueId];
  91295. }
  91296. this._shouldRender = false;
  91297. for (var meshHighlightToCheck in this._meshes) {
  91298. if (this._meshes[meshHighlightToCheck]) {
  91299. this._shouldRender = true;
  91300. break;
  91301. }
  91302. }
  91303. };
  91304. /**
  91305. * Force the stencil to the normal expected value for none glowing parts
  91306. */
  91307. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91308. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91309. };
  91310. /**
  91311. * Free any resources and references associated to a mesh.
  91312. * Internal use
  91313. * @param mesh The mesh to free.
  91314. */
  91315. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91316. this.removeMesh(mesh);
  91317. this.removeExcludedMesh(mesh);
  91318. };
  91319. /**
  91320. * Dispose the highlight layer and free resources.
  91321. */
  91322. HighlightLayer.prototype.dispose = function () {
  91323. if (this._meshes) {
  91324. // Clean mesh references
  91325. for (var id in this._meshes) {
  91326. var meshHighlight = this._meshes[id];
  91327. if (meshHighlight && meshHighlight.mesh) {
  91328. if (meshHighlight.observerHighlight) {
  91329. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91330. }
  91331. if (meshHighlight.observerDefault) {
  91332. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91333. }
  91334. }
  91335. }
  91336. this._meshes = null;
  91337. }
  91338. if (this._excludedMeshes) {
  91339. for (var id in this._excludedMeshes) {
  91340. var meshHighlight = this._excludedMeshes[id];
  91341. if (meshHighlight) {
  91342. if (meshHighlight.beforeRender) {
  91343. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91344. }
  91345. if (meshHighlight.afterRender) {
  91346. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91347. }
  91348. }
  91349. }
  91350. this._excludedMeshes = null;
  91351. }
  91352. _super.prototype.dispose.call(this);
  91353. };
  91354. /**
  91355. * Gets the class name of the effect layer
  91356. * @returns the string with the class name of the effect layer
  91357. */
  91358. HighlightLayer.prototype.getClassName = function () {
  91359. return "HighlightLayer";
  91360. };
  91361. /**
  91362. * Serializes this Highlight layer
  91363. * @returns a serialized Highlight layer object
  91364. */
  91365. HighlightLayer.prototype.serialize = function () {
  91366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91367. serializationObject.customType = "BABYLON.HighlightLayer";
  91368. // Highlighted meshes
  91369. serializationObject.meshes = [];
  91370. if (this._meshes) {
  91371. for (var m in this._meshes) {
  91372. var mesh = this._meshes[m];
  91373. if (mesh) {
  91374. serializationObject.meshes.push({
  91375. glowEmissiveOnly: mesh.glowEmissiveOnly,
  91376. color: mesh.color.asArray(),
  91377. meshId: mesh.mesh.id
  91378. });
  91379. }
  91380. }
  91381. }
  91382. // Excluded meshes
  91383. serializationObject.excludedMeshes = [];
  91384. if (this._excludedMeshes) {
  91385. for (var e in this._excludedMeshes) {
  91386. var excludedMesh = this._excludedMeshes[e];
  91387. if (excludedMesh) {
  91388. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  91389. }
  91390. }
  91391. }
  91392. return serializationObject;
  91393. };
  91394. /**
  91395. * Creates a Highlight layer from parsed Highlight layer data
  91396. * @param parsedHightlightLayer defines the Highlight layer data
  91397. * @param scene defines the current scene
  91398. * @param rootUrl defines the root URL containing the Highlight layer information
  91399. * @returns a parsed Highlight layer
  91400. */
  91401. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  91402. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  91403. var index;
  91404. // Excluded meshes
  91405. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  91406. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  91407. if (mesh) {
  91408. hl.addExcludedMesh(mesh);
  91409. }
  91410. }
  91411. // Included meshes
  91412. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  91413. var highlightedMesh = parsedHightlightLayer.meshes[index];
  91414. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  91415. if (mesh) {
  91416. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  91417. }
  91418. }
  91419. return hl;
  91420. };
  91421. /**
  91422. * Effect Name of the highlight layer.
  91423. */
  91424. HighlightLayer.EffectName = "HighlightLayer";
  91425. /**
  91426. * The neutral color used during the preparation of the glow effect.
  91427. * This is black by default as the blend operation is a blend operation.
  91428. */
  91429. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  91430. /**
  91431. * Stencil value used for glowing meshes.
  91432. */
  91433. HighlightLayer.GlowingMeshStencilReference = 0x02;
  91434. /**
  91435. * Stencil value used for the other meshes in the scene.
  91436. */
  91437. HighlightLayer.NormalMeshStencilReference = 0x01;
  91438. __decorate([
  91439. BABYLON.serialize()
  91440. ], HighlightLayer.prototype, "innerGlow", void 0);
  91441. __decorate([
  91442. BABYLON.serialize()
  91443. ], HighlightLayer.prototype, "outerGlow", void 0);
  91444. __decorate([
  91445. BABYLON.serialize()
  91446. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  91447. __decorate([
  91448. BABYLON.serialize()
  91449. ], HighlightLayer.prototype, "blurVerticalSize", null);
  91450. __decorate([
  91451. BABYLON.serialize("options")
  91452. ], HighlightLayer.prototype, "_options", void 0);
  91453. return HighlightLayer;
  91454. }(BABYLON.EffectLayer));
  91455. BABYLON.HighlightLayer = HighlightLayer;
  91456. })(BABYLON || (BABYLON = {}));
  91457. //# sourceMappingURL=babylon.highlightLayer.js.map
  91458. var BABYLON;
  91459. (function (BABYLON) {
  91460. /**
  91461. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  91462. *
  91463. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91464. * glowy meshes to your scene.
  91465. *
  91466. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  91467. */
  91468. var GlowLayer = /** @class */ (function (_super) {
  91469. __extends(GlowLayer, _super);
  91470. /**
  91471. * Instantiates a new glow Layer and references it to the scene.
  91472. * @param name The name of the layer
  91473. * @param scene The scene to use the layer in
  91474. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  91475. */
  91476. function GlowLayer(name, scene, options) {
  91477. var _this = _super.call(this, name, scene) || this;
  91478. _this._intensity = 1.0;
  91479. _this._includedOnlyMeshes = [];
  91480. _this._excludedMeshes = [];
  91481. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  91482. // Adapt options
  91483. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  91484. // Initialize the layer
  91485. _this._init({
  91486. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  91487. camera: _this._options.camera,
  91488. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91489. mainTextureRatio: _this._options.mainTextureRatio
  91490. });
  91491. return _this;
  91492. }
  91493. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  91494. /**
  91495. * Gets the kernel size of the blur.
  91496. */
  91497. get: function () {
  91498. return this._horizontalBlurPostprocess1.kernel;
  91499. },
  91500. /**
  91501. * Sets the kernel size of the blur.
  91502. */
  91503. set: function (value) {
  91504. this._horizontalBlurPostprocess1.kernel = value;
  91505. this._verticalBlurPostprocess1.kernel = value;
  91506. this._horizontalBlurPostprocess2.kernel = value;
  91507. this._verticalBlurPostprocess2.kernel = value;
  91508. },
  91509. enumerable: true,
  91510. configurable: true
  91511. });
  91512. Object.defineProperty(GlowLayer.prototype, "intensity", {
  91513. /**
  91514. * Gets the glow intensity.
  91515. */
  91516. get: function () {
  91517. return this._intensity;
  91518. },
  91519. /**
  91520. * Sets the glow intensity.
  91521. */
  91522. set: function (value) {
  91523. this._intensity = value;
  91524. },
  91525. enumerable: true,
  91526. configurable: true
  91527. });
  91528. /**
  91529. * Get the effect name of the layer.
  91530. * @return The effect name
  91531. */
  91532. GlowLayer.prototype.getEffectName = function () {
  91533. return GlowLayer.EffectName;
  91534. };
  91535. /**
  91536. * Create the merge effect. This is the shader use to blit the information back
  91537. * to the main canvas at the end of the scene rendering.
  91538. */
  91539. GlowLayer.prototype._createMergeEffect = function () {
  91540. // Effect
  91541. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  91542. };
  91543. /**
  91544. * Creates the render target textures and post processes used in the glow layer.
  91545. */
  91546. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  91547. var _this = this;
  91548. var blurTextureWidth = this._mainTextureDesiredSize.width;
  91549. var blurTextureHeight = this._mainTextureDesiredSize.height;
  91550. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91551. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91552. var textureType = 0;
  91553. if (this._engine.getCaps().textureHalfFloatRender) {
  91554. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91555. }
  91556. else {
  91557. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91558. }
  91559. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  91560. width: blurTextureWidth,
  91561. height: blurTextureHeight
  91562. }, this._scene, false, true, textureType);
  91563. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91564. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91565. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91566. this._blurTexture1.renderParticles = false;
  91567. this._blurTexture1.ignoreCameraViewport = true;
  91568. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  91569. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  91570. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  91571. width: blurTextureWidth2,
  91572. height: blurTextureHeight2
  91573. }, this._scene, false, true, textureType);
  91574. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91575. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91576. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91577. this._blurTexture2.renderParticles = false;
  91578. this._blurTexture2.ignoreCameraViewport = true;
  91579. this._textures = [this._blurTexture1, this._blurTexture2];
  91580. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91581. width: blurTextureWidth,
  91582. height: blurTextureHeight
  91583. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91584. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  91585. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  91586. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  91587. effect.setTexture("textureSampler", _this._mainTexture);
  91588. });
  91589. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91590. width: blurTextureWidth,
  91591. height: blurTextureHeight
  91592. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91593. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91594. width: blurTextureWidth2,
  91595. height: blurTextureHeight2
  91596. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91597. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91598. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91599. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91600. effect.setTexture("textureSampler", _this._blurTexture1);
  91601. });
  91602. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91603. width: blurTextureWidth2,
  91604. height: blurTextureHeight2
  91605. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91606. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91607. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91608. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91609. this._mainTexture.samples = this._options.mainTextureSamples;
  91610. this._mainTexture.onAfterUnbindObservable.add(function () {
  91611. var internalTexture = _this._blurTexture1.getInternalTexture();
  91612. if (internalTexture) {
  91613. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91614. internalTexture = _this._blurTexture2.getInternalTexture();
  91615. if (internalTexture) {
  91616. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91617. }
  91618. }
  91619. });
  91620. // Prevent autoClear.
  91621. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91622. };
  91623. /**
  91624. * Checks for the readiness of the element composing the layer.
  91625. * @param subMesh the mesh to check for
  91626. * @param useInstances specify wether or not to use instances to render the mesh
  91627. * @param emissiveTexture the associated emissive texture used to generate the glow
  91628. * @return true if ready otherwise, false
  91629. */
  91630. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91631. var material = subMesh.getMaterial();
  91632. var mesh = subMesh.getRenderingMesh();
  91633. if (!material || !mesh) {
  91634. return false;
  91635. }
  91636. var emissiveTexture = material.emissiveTexture;
  91637. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91638. };
  91639. /**
  91640. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91641. */
  91642. GlowLayer.prototype.needStencil = function () {
  91643. return false;
  91644. };
  91645. /**
  91646. * Implementation specific of rendering the generating effect on the main canvas.
  91647. * @param effect The effect used to render through
  91648. */
  91649. GlowLayer.prototype._internalRender = function (effect) {
  91650. // Texture
  91651. effect.setTexture("textureSampler", this._blurTexture1);
  91652. effect.setTexture("textureSampler2", this._blurTexture2);
  91653. effect.setFloat("offset", this._intensity);
  91654. // Cache
  91655. var engine = this._engine;
  91656. var previousStencilBuffer = engine.getStencilBuffer();
  91657. // Draw order
  91658. engine.setStencilBuffer(false);
  91659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91660. // Draw order
  91661. engine.setStencilBuffer(previousStencilBuffer);
  91662. };
  91663. /**
  91664. * Sets the required values for both the emissive texture and and the main color.
  91665. */
  91666. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91667. var textureLevel = 1.0;
  91668. if (this.customEmissiveTextureSelector) {
  91669. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91670. }
  91671. else {
  91672. if (material) {
  91673. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91674. if (this._emissiveTextureAndColor.texture) {
  91675. textureLevel = this._emissiveTextureAndColor.texture.level;
  91676. }
  91677. }
  91678. else {
  91679. this._emissiveTextureAndColor.texture = null;
  91680. }
  91681. }
  91682. if (this.customEmissiveColorSelector) {
  91683. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91684. }
  91685. else {
  91686. if (material.emissiveColor) {
  91687. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91688. }
  91689. else {
  91690. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91691. }
  91692. }
  91693. };
  91694. /**
  91695. * Returns true if the mesh should render, otherwise false.
  91696. * @param mesh The mesh to render
  91697. * @returns true if it should render otherwise false
  91698. */
  91699. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91700. return this.hasMesh(mesh);
  91701. };
  91702. /**
  91703. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91704. * @param mesh The mesh to exclude from the glow layer
  91705. */
  91706. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91707. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91708. this._excludedMeshes.push(mesh.uniqueId);
  91709. }
  91710. };
  91711. /**
  91712. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91713. * @param mesh The mesh to remove
  91714. */
  91715. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91716. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91717. if (index !== -1) {
  91718. this._excludedMeshes.splice(index, 1);
  91719. }
  91720. };
  91721. /**
  91722. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91723. * @param mesh The mesh to include in the glow layer
  91724. */
  91725. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91726. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91727. this._includedOnlyMeshes.push(mesh.uniqueId);
  91728. }
  91729. };
  91730. /**
  91731. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91732. * @param mesh The mesh to remove
  91733. */
  91734. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91735. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91736. if (index !== -1) {
  91737. this._includedOnlyMeshes.splice(index, 1);
  91738. }
  91739. };
  91740. /**
  91741. * Determine if a given mesh will be used in the glow layer
  91742. * @param mesh The mesh to test
  91743. * @returns true if the mesh will be highlighted by the current glow layer
  91744. */
  91745. GlowLayer.prototype.hasMesh = function (mesh) {
  91746. // Included Mesh
  91747. if (this._includedOnlyMeshes.length) {
  91748. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91749. }
  91750. ;
  91751. // Excluded Mesh
  91752. if (this._excludedMeshes.length) {
  91753. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91754. }
  91755. ;
  91756. return true;
  91757. };
  91758. /**
  91759. * Free any resources and references associated to a mesh.
  91760. * Internal use
  91761. * @param mesh The mesh to free.
  91762. */
  91763. GlowLayer.prototype._disposeMesh = function (mesh) {
  91764. this.removeIncludedOnlyMesh(mesh);
  91765. this.removeExcludedMesh(mesh);
  91766. };
  91767. /**
  91768. * Gets the class name of the effect layer
  91769. * @returns the string with the class name of the effect layer
  91770. */
  91771. GlowLayer.prototype.getClassName = function () {
  91772. return "GlowLayer";
  91773. };
  91774. /**
  91775. * Serializes this glow layer
  91776. * @returns a serialized glow layer object
  91777. */
  91778. GlowLayer.prototype.serialize = function () {
  91779. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91780. serializationObject.customType = "BABYLON.GlowLayer";
  91781. var index;
  91782. // Included meshes
  91783. serializationObject.includedMeshes = [];
  91784. if (this._includedOnlyMeshes.length) {
  91785. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91786. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91787. if (mesh) {
  91788. serializationObject.includedMeshes.push(mesh.id);
  91789. }
  91790. }
  91791. }
  91792. // Excluded meshes
  91793. serializationObject.excludedMeshes = [];
  91794. if (this._excludedMeshes.length) {
  91795. for (index = 0; index < this._excludedMeshes.length; index++) {
  91796. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91797. if (mesh) {
  91798. serializationObject.excludedMeshes.push(mesh.id);
  91799. }
  91800. }
  91801. }
  91802. return serializationObject;
  91803. };
  91804. /**
  91805. * Creates a Glow Layer from parsed glow layer data
  91806. * @param parsedGlowLayer defines glow layer data
  91807. * @param scene defines the current scene
  91808. * @param rootUrl defines the root URL containing the glow layer information
  91809. * @returns a parsed Glow Layer
  91810. */
  91811. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91812. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91813. var index;
  91814. // Excluded meshes
  91815. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91816. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91817. if (mesh) {
  91818. gl.addExcludedMesh(mesh);
  91819. }
  91820. }
  91821. // Included meshes
  91822. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91823. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91824. if (mesh) {
  91825. gl.addIncludedOnlyMesh(mesh);
  91826. }
  91827. }
  91828. return gl;
  91829. };
  91830. /**
  91831. * Effect Name of the layer.
  91832. */
  91833. GlowLayer.EffectName = "GlowLayer";
  91834. /**
  91835. * The default blur kernel size used for the glow.
  91836. */
  91837. GlowLayer.DefaultBlurKernelSize = 32;
  91838. /**
  91839. * The default texture size ratio used for the glow.
  91840. */
  91841. GlowLayer.DefaultTextureRatio = 0.5;
  91842. __decorate([
  91843. BABYLON.serialize()
  91844. ], GlowLayer.prototype, "blurKernelSize", null);
  91845. __decorate([
  91846. BABYLON.serialize()
  91847. ], GlowLayer.prototype, "intensity", null);
  91848. __decorate([
  91849. BABYLON.serialize("options")
  91850. ], GlowLayer.prototype, "_options", void 0);
  91851. return GlowLayer;
  91852. }(BABYLON.EffectLayer));
  91853. BABYLON.GlowLayer = GlowLayer;
  91854. })(BABYLON || (BABYLON = {}));
  91855. //# sourceMappingURL=babylon.glowLayer.js.map
  91856. var BABYLON;
  91857. (function (BABYLON) {
  91858. /**
  91859. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91860. */
  91861. var AssetTaskState;
  91862. (function (AssetTaskState) {
  91863. /**
  91864. * Initialization
  91865. */
  91866. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91867. /**
  91868. * Running
  91869. */
  91870. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91871. /**
  91872. * Done
  91873. */
  91874. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91875. /**
  91876. * Error
  91877. */
  91878. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91879. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91880. /**
  91881. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91882. */
  91883. var AbstractAssetTask = /** @class */ (function () {
  91884. /**
  91885. * Creates a new {BABYLON.AssetsManager}
  91886. * @param name defines the name of the task
  91887. */
  91888. function AbstractAssetTask(
  91889. /**
  91890. * Task name
  91891. */ name) {
  91892. this.name = name;
  91893. this._isCompleted = false;
  91894. this._taskState = AssetTaskState.INIT;
  91895. }
  91896. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91897. /**
  91898. * Get if the task is completed
  91899. */
  91900. get: function () {
  91901. return this._isCompleted;
  91902. },
  91903. enumerable: true,
  91904. configurable: true
  91905. });
  91906. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91907. /**
  91908. * Gets the current state of the task
  91909. */
  91910. get: function () {
  91911. return this._taskState;
  91912. },
  91913. enumerable: true,
  91914. configurable: true
  91915. });
  91916. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91917. /**
  91918. * Gets the current error object (if task is in error)
  91919. */
  91920. get: function () {
  91921. return this._errorObject;
  91922. },
  91923. enumerable: true,
  91924. configurable: true
  91925. });
  91926. /**
  91927. * Internal only
  91928. * @ignore
  91929. */
  91930. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91931. if (this._errorObject) {
  91932. return;
  91933. }
  91934. this._errorObject = {
  91935. message: message,
  91936. exception: exception
  91937. };
  91938. };
  91939. /**
  91940. * Execute the current task
  91941. * @param scene defines the scene where you want your assets to be loaded
  91942. * @param onSuccess is a callback called when the task is successfully executed
  91943. * @param onError is a callback called if an error occurs
  91944. */
  91945. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91946. var _this = this;
  91947. this._taskState = AssetTaskState.RUNNING;
  91948. this.runTask(scene, function () {
  91949. _this.onDoneCallback(onSuccess, onError);
  91950. }, function (msg, exception) {
  91951. _this.onErrorCallback(onError, msg, exception);
  91952. });
  91953. };
  91954. /**
  91955. * Execute the current task
  91956. * @param scene defines the scene where you want your assets to be loaded
  91957. * @param onSuccess is a callback called when the task is successfully executed
  91958. * @param onError is a callback called if an error occurs
  91959. */
  91960. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91961. throw new Error("runTask is not implemented");
  91962. };
  91963. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91964. this._taskState = AssetTaskState.ERROR;
  91965. this._errorObject = {
  91966. message: message,
  91967. exception: exception
  91968. };
  91969. if (this.onError) {
  91970. this.onError(this, message, exception);
  91971. }
  91972. onError();
  91973. };
  91974. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91975. try {
  91976. this._taskState = AssetTaskState.DONE;
  91977. this._isCompleted = true;
  91978. if (this.onSuccess) {
  91979. this.onSuccess(this);
  91980. }
  91981. onSuccess();
  91982. }
  91983. catch (e) {
  91984. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91985. }
  91986. };
  91987. return AbstractAssetTask;
  91988. }());
  91989. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91990. /**
  91991. * Class used to share progress information about assets loading
  91992. */
  91993. var AssetsProgressEvent = /** @class */ (function () {
  91994. /**
  91995. * Creates a {BABYLON.AssetsProgressEvent}
  91996. * @param remainingCount defines the number of remaining tasks to process
  91997. * @param totalCount defines the total number of tasks
  91998. * @param task defines the task that was just processed
  91999. */
  92000. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92001. this.remainingCount = remainingCount;
  92002. this.totalCount = totalCount;
  92003. this.task = task;
  92004. }
  92005. return AssetsProgressEvent;
  92006. }());
  92007. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92008. /**
  92009. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92010. */
  92011. var MeshAssetTask = /** @class */ (function (_super) {
  92012. __extends(MeshAssetTask, _super);
  92013. /**
  92014. * Creates a new {BABYLON.MeshAssetTask}
  92015. * @param name defines the name of the task
  92016. * @param meshesNames defines the list of mesh's names you want to load
  92017. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92018. * @param sceneFilename defines the filename of the scene to load from
  92019. */
  92020. function MeshAssetTask(
  92021. /**
  92022. * Defines the name of the task
  92023. */
  92024. name,
  92025. /**
  92026. * Defines the list of mesh's names you want to load
  92027. */
  92028. meshesNames,
  92029. /**
  92030. * Defines the root url to use as a base to load your meshes and associated resources
  92031. */
  92032. rootUrl,
  92033. /**
  92034. * Defines the filename of the scene to load from
  92035. */
  92036. sceneFilename) {
  92037. var _this = _super.call(this, name) || this;
  92038. _this.name = name;
  92039. _this.meshesNames = meshesNames;
  92040. _this.rootUrl = rootUrl;
  92041. _this.sceneFilename = sceneFilename;
  92042. return _this;
  92043. }
  92044. /**
  92045. * Execute the current task
  92046. * @param scene defines the scene where you want your assets to be loaded
  92047. * @param onSuccess is a callback called when the task is successfully executed
  92048. * @param onError is a callback called if an error occurs
  92049. */
  92050. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92051. var _this = this;
  92052. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92053. _this.loadedMeshes = meshes;
  92054. _this.loadedParticleSystems = particleSystems;
  92055. _this.loadedSkeletons = skeletons;
  92056. onSuccess();
  92057. }, null, function (scene, message, exception) {
  92058. onError(message, exception);
  92059. });
  92060. };
  92061. return MeshAssetTask;
  92062. }(AbstractAssetTask));
  92063. BABYLON.MeshAssetTask = MeshAssetTask;
  92064. /**
  92065. * Define a task used by {BABYLON.AssetsManager} to load text content
  92066. */
  92067. var TextFileAssetTask = /** @class */ (function (_super) {
  92068. __extends(TextFileAssetTask, _super);
  92069. /**
  92070. * Creates a new TextFileAssetTask object
  92071. * @param name defines the name of the task
  92072. * @param url defines the location of the file to load
  92073. */
  92074. function TextFileAssetTask(
  92075. /**
  92076. * Defines the name of the task
  92077. */
  92078. name,
  92079. /**
  92080. * Defines the location of the file to load
  92081. */
  92082. url) {
  92083. var _this = _super.call(this, name) || this;
  92084. _this.name = name;
  92085. _this.url = url;
  92086. return _this;
  92087. }
  92088. /**
  92089. * Execute the current task
  92090. * @param scene defines the scene where you want your assets to be loaded
  92091. * @param onSuccess is a callback called when the task is successfully executed
  92092. * @param onError is a callback called if an error occurs
  92093. */
  92094. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92095. var _this = this;
  92096. scene._loadFile(this.url, function (data) {
  92097. _this.text = data;
  92098. onSuccess();
  92099. }, undefined, false, false, function (request, exception) {
  92100. if (request) {
  92101. onError(request.status + " " + request.statusText, exception);
  92102. }
  92103. });
  92104. };
  92105. return TextFileAssetTask;
  92106. }(AbstractAssetTask));
  92107. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92108. /**
  92109. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92110. */
  92111. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92112. __extends(BinaryFileAssetTask, _super);
  92113. /**
  92114. * Creates a new BinaryFileAssetTask object
  92115. * @param name defines the name of the new task
  92116. * @param url defines the location of the file to load
  92117. */
  92118. function BinaryFileAssetTask(
  92119. /**
  92120. * Defines the name of the task
  92121. */
  92122. name,
  92123. /**
  92124. * Defines the location of the file to load
  92125. */
  92126. url) {
  92127. var _this = _super.call(this, name) || this;
  92128. _this.name = name;
  92129. _this.url = url;
  92130. return _this;
  92131. }
  92132. /**
  92133. * Execute the current task
  92134. * @param scene defines the scene where you want your assets to be loaded
  92135. * @param onSuccess is a callback called when the task is successfully executed
  92136. * @param onError is a callback called if an error occurs
  92137. */
  92138. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92139. var _this = this;
  92140. scene._loadFile(this.url, function (data) {
  92141. _this.data = data;
  92142. onSuccess();
  92143. }, undefined, true, true, function (request, exception) {
  92144. if (request) {
  92145. onError(request.status + " " + request.statusText, exception);
  92146. }
  92147. });
  92148. };
  92149. return BinaryFileAssetTask;
  92150. }(AbstractAssetTask));
  92151. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92152. /**
  92153. * Define a task used by {BABYLON.AssetsManager} to load images
  92154. */
  92155. var ImageAssetTask = /** @class */ (function (_super) {
  92156. __extends(ImageAssetTask, _super);
  92157. /**
  92158. * Creates a new ImageAssetTask
  92159. * @param name defines the name of the task
  92160. * @param url defines the location of the image to load
  92161. */
  92162. function ImageAssetTask(
  92163. /**
  92164. * Defines the name of the task
  92165. */
  92166. name,
  92167. /**
  92168. * Defines the location of the image to load
  92169. */
  92170. url) {
  92171. var _this = _super.call(this, name) || this;
  92172. _this.name = name;
  92173. _this.url = url;
  92174. return _this;
  92175. }
  92176. /**
  92177. * Execute the current task
  92178. * @param scene defines the scene where you want your assets to be loaded
  92179. * @param onSuccess is a callback called when the task is successfully executed
  92180. * @param onError is a callback called if an error occurs
  92181. */
  92182. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92183. var _this = this;
  92184. var img = new Image();
  92185. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92186. img.onload = function () {
  92187. _this.image = img;
  92188. onSuccess();
  92189. };
  92190. img.onerror = function (err) {
  92191. onError("Error loading image", err);
  92192. };
  92193. img.src = this.url;
  92194. };
  92195. return ImageAssetTask;
  92196. }(AbstractAssetTask));
  92197. BABYLON.ImageAssetTask = ImageAssetTask;
  92198. /**
  92199. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92200. */
  92201. var TextureAssetTask = /** @class */ (function (_super) {
  92202. __extends(TextureAssetTask, _super);
  92203. /**
  92204. * Creates a new TextureAssetTask object
  92205. * @param name defines the name of the task
  92206. * @param url defines the location of the file to load
  92207. * @param noMipmap defines if mipmap should not be generated (default is false)
  92208. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92209. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92210. */
  92211. function TextureAssetTask(
  92212. /**
  92213. * Defines the name of the task
  92214. */
  92215. name,
  92216. /**
  92217. * Defines the location of the file to load
  92218. */
  92219. url,
  92220. /**
  92221. * Defines if mipmap should not be generated (default is false)
  92222. */
  92223. noMipmap,
  92224. /**
  92225. * Defines if texture must be inverted on Y axis (default is false)
  92226. */
  92227. invertY,
  92228. /**
  92229. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92230. */
  92231. samplingMode) {
  92232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92233. var _this = _super.call(this, name) || this;
  92234. _this.name = name;
  92235. _this.url = url;
  92236. _this.noMipmap = noMipmap;
  92237. _this.invertY = invertY;
  92238. _this.samplingMode = samplingMode;
  92239. return _this;
  92240. }
  92241. /**
  92242. * Execute the current task
  92243. * @param scene defines the scene where you want your assets to be loaded
  92244. * @param onSuccess is a callback called when the task is successfully executed
  92245. * @param onError is a callback called if an error occurs
  92246. */
  92247. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92248. var onload = function () {
  92249. onSuccess();
  92250. };
  92251. var onerror = function (message, exception) {
  92252. onError(message, exception);
  92253. };
  92254. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92255. };
  92256. return TextureAssetTask;
  92257. }(AbstractAssetTask));
  92258. BABYLON.TextureAssetTask = TextureAssetTask;
  92259. /**
  92260. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92261. */
  92262. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92263. __extends(CubeTextureAssetTask, _super);
  92264. /**
  92265. * Creates a new CubeTextureAssetTask
  92266. * @param name defines the name of the task
  92267. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92268. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92269. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92270. * @param files defines the explicit list of files (undefined by default)
  92271. */
  92272. function CubeTextureAssetTask(
  92273. /**
  92274. * Defines the name of the task
  92275. */
  92276. name,
  92277. /**
  92278. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92279. */
  92280. url,
  92281. /**
  92282. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92283. */
  92284. extensions,
  92285. /**
  92286. * Defines if mipmaps should not be generated (default is false)
  92287. */
  92288. noMipmap,
  92289. /**
  92290. * Defines the explicit list of files (undefined by default)
  92291. */
  92292. files) {
  92293. var _this = _super.call(this, name) || this;
  92294. _this.name = name;
  92295. _this.url = url;
  92296. _this.extensions = extensions;
  92297. _this.noMipmap = noMipmap;
  92298. _this.files = files;
  92299. return _this;
  92300. }
  92301. /**
  92302. * Execute the current task
  92303. * @param scene defines the scene where you want your assets to be loaded
  92304. * @param onSuccess is a callback called when the task is successfully executed
  92305. * @param onError is a callback called if an error occurs
  92306. */
  92307. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92308. var onload = function () {
  92309. onSuccess();
  92310. };
  92311. var onerror = function (message, exception) {
  92312. onError(message, exception);
  92313. };
  92314. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92315. };
  92316. return CubeTextureAssetTask;
  92317. }(AbstractAssetTask));
  92318. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92319. /**
  92320. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92321. */
  92322. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92323. __extends(HDRCubeTextureAssetTask, _super);
  92324. /**
  92325. * Creates a new HDRCubeTextureAssetTask object
  92326. * @param name defines the name of the task
  92327. * @param url defines the location of the file to load
  92328. * @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.
  92329. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92330. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92331. * @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)
  92332. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92333. */
  92334. function HDRCubeTextureAssetTask(
  92335. /**
  92336. * Defines the name of the task
  92337. */
  92338. name,
  92339. /**
  92340. * Defines the location of the file to load
  92341. */
  92342. url,
  92343. /**
  92344. * 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.
  92345. */
  92346. size,
  92347. /**
  92348. * Defines if mipmaps should not be generated (default is false)
  92349. */
  92350. noMipmap,
  92351. /**
  92352. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92353. */
  92354. generateHarmonics,
  92355. /**
  92356. * 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)
  92357. */
  92358. useInGammaSpace,
  92359. /**
  92360. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92361. */
  92362. usePMREMGenerator) {
  92363. if (noMipmap === void 0) { noMipmap = false; }
  92364. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92365. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92366. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92367. var _this = _super.call(this, name) || this;
  92368. _this.name = name;
  92369. _this.url = url;
  92370. _this.size = size;
  92371. _this.noMipmap = noMipmap;
  92372. _this.generateHarmonics = generateHarmonics;
  92373. _this.useInGammaSpace = useInGammaSpace;
  92374. _this.usePMREMGenerator = usePMREMGenerator;
  92375. return _this;
  92376. }
  92377. /**
  92378. * Execute the current task
  92379. * @param scene defines the scene where you want your assets to be loaded
  92380. * @param onSuccess is a callback called when the task is successfully executed
  92381. * @param onError is a callback called if an error occurs
  92382. */
  92383. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92384. var onload = function () {
  92385. onSuccess();
  92386. };
  92387. var onerror = function (message, exception) {
  92388. onError(message, exception);
  92389. };
  92390. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  92391. };
  92392. return HDRCubeTextureAssetTask;
  92393. }(AbstractAssetTask));
  92394. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  92395. /**
  92396. * This class can be used to easily import assets into a scene
  92397. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  92398. */
  92399. var AssetsManager = /** @class */ (function () {
  92400. /**
  92401. * Creates a new AssetsManager
  92402. * @param scene defines the scene to work on
  92403. */
  92404. function AssetsManager(scene) {
  92405. this._isLoading = false;
  92406. this._tasks = new Array();
  92407. this._waitingTasksCount = 0;
  92408. this._totalTasksCount = 0;
  92409. /**
  92410. * Observable called when all tasks are processed
  92411. */
  92412. this.onTaskSuccessObservable = new BABYLON.Observable();
  92413. /**
  92414. * Observable called when a task had an error
  92415. */
  92416. this.onTaskErrorObservable = new BABYLON.Observable();
  92417. /**
  92418. * Observable called when a task is successful
  92419. */
  92420. this.onTasksDoneObservable = new BABYLON.Observable();
  92421. /**
  92422. * Observable called when a task is done (whatever the result is)
  92423. */
  92424. this.onProgressObservable = new BABYLON.Observable();
  92425. /**
  92426. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  92427. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  92428. */
  92429. this.useDefaultLoadingScreen = true;
  92430. this._scene = scene;
  92431. }
  92432. /**
  92433. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  92434. * @param taskName defines the name of the new task
  92435. * @param meshesNames defines the name of meshes to load
  92436. * @param rootUrl defines the root url to use to locate files
  92437. * @param sceneFilename defines the filename of the scene file
  92438. * @returns a new {BABYLON.MeshAssetTask} object
  92439. */
  92440. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  92441. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  92442. this._tasks.push(task);
  92443. return task;
  92444. };
  92445. /**
  92446. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  92447. * @param taskName defines the name of the new task
  92448. * @param url defines the url of the file to load
  92449. * @returns a new {BABYLON.TextFileAssetTask} object
  92450. */
  92451. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  92452. var task = new TextFileAssetTask(taskName, url);
  92453. this._tasks.push(task);
  92454. return task;
  92455. };
  92456. /**
  92457. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  92458. * @param taskName defines the name of the new task
  92459. * @param url defines the url of the file to load
  92460. * @returns a new {BABYLON.BinaryFileAssetTask} object
  92461. */
  92462. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  92463. var task = new BinaryFileAssetTask(taskName, url);
  92464. this._tasks.push(task);
  92465. return task;
  92466. };
  92467. /**
  92468. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  92469. * @param taskName defines the name of the new task
  92470. * @param url defines the url of the file to load
  92471. * @returns a new {BABYLON.ImageAssetTask} object
  92472. */
  92473. AssetsManager.prototype.addImageTask = function (taskName, url) {
  92474. var task = new ImageAssetTask(taskName, url);
  92475. this._tasks.push(task);
  92476. return task;
  92477. };
  92478. /**
  92479. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  92480. * @param taskName defines the name of the new task
  92481. * @param url defines the url of the file to load
  92482. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92483. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  92484. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  92485. * @returns a new {BABYLON.TextureAssetTask} object
  92486. */
  92487. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  92488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92489. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  92490. this._tasks.push(task);
  92491. return task;
  92492. };
  92493. /**
  92494. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  92495. * @param taskName defines the name of the new task
  92496. * @param url defines the url of the file to load
  92497. * @param extensions defines the extension to use to load the cube map (can be null)
  92498. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92499. * @param files defines the list of files to load (can be null)
  92500. * @returns a new {BABYLON.CubeTextureAssetTask} object
  92501. */
  92502. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  92503. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  92504. this._tasks.push(task);
  92505. return task;
  92506. };
  92507. /**
  92508. *
  92509. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  92510. * @param taskName defines the name of the new task
  92511. * @param url defines the url of the file to load
  92512. * @param size defines the size you want for the cubemap (can be null)
  92513. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92514. * @param generateHarmonics defines if you want to automatically generate (true by default)
  92515. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  92516. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  92517. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  92518. */
  92519. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  92520. if (noMipmap === void 0) { noMipmap = false; }
  92521. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92522. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92523. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92524. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  92525. this._tasks.push(task);
  92526. return task;
  92527. };
  92528. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  92529. var _this = this;
  92530. this._waitingTasksCount--;
  92531. try {
  92532. if (task.taskState === AssetTaskState.DONE) {
  92533. // Let's remove successfull tasks
  92534. BABYLON.Tools.SetImmediate(function () {
  92535. var index = _this._tasks.indexOf(task);
  92536. if (index > -1) {
  92537. _this._tasks.splice(index, 1);
  92538. }
  92539. });
  92540. }
  92541. if (this.onProgress) {
  92542. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  92543. }
  92544. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  92545. }
  92546. catch (e) {
  92547. BABYLON.Tools.Error("Error running progress callbacks.");
  92548. console.log(e);
  92549. }
  92550. if (this._waitingTasksCount === 0) {
  92551. try {
  92552. if (this.onFinish) {
  92553. this.onFinish(this._tasks);
  92554. }
  92555. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92556. }
  92557. catch (e) {
  92558. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  92559. console.log(e);
  92560. }
  92561. this._isLoading = false;
  92562. this._scene.getEngine().hideLoadingUI();
  92563. }
  92564. };
  92565. AssetsManager.prototype._runTask = function (task) {
  92566. var _this = this;
  92567. var done = function () {
  92568. try {
  92569. if (_this.onTaskSuccess) {
  92570. _this.onTaskSuccess(task);
  92571. }
  92572. _this.onTaskSuccessObservable.notifyObservers(task);
  92573. _this._decreaseWaitingTasksCount(task);
  92574. }
  92575. catch (e) {
  92576. error("Error executing task success callbacks", e);
  92577. }
  92578. };
  92579. var error = function (message, exception) {
  92580. task._setErrorObject(message, exception);
  92581. if (_this.onTaskError) {
  92582. _this.onTaskError(task);
  92583. }
  92584. _this.onTaskErrorObservable.notifyObservers(task);
  92585. _this._decreaseWaitingTasksCount(task);
  92586. };
  92587. task.run(this._scene, done, error);
  92588. };
  92589. /**
  92590. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92591. * @return the current instance of the {BABYLON.AssetsManager}
  92592. */
  92593. AssetsManager.prototype.reset = function () {
  92594. this._isLoading = false;
  92595. this._tasks = new Array();
  92596. return this;
  92597. };
  92598. /**
  92599. * Start the loading process
  92600. * @return the current instance of the {BABYLON.AssetsManager}
  92601. */
  92602. AssetsManager.prototype.load = function () {
  92603. if (this._isLoading) {
  92604. return this;
  92605. }
  92606. this._isLoading = true;
  92607. this._waitingTasksCount = this._tasks.length;
  92608. this._totalTasksCount = this._tasks.length;
  92609. if (this._waitingTasksCount === 0) {
  92610. this._isLoading = false;
  92611. if (this.onFinish) {
  92612. this.onFinish(this._tasks);
  92613. }
  92614. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92615. return this;
  92616. }
  92617. if (this.useDefaultLoadingScreen) {
  92618. this._scene.getEngine().displayLoadingUI();
  92619. }
  92620. for (var index = 0; index < this._tasks.length; index++) {
  92621. var task = this._tasks[index];
  92622. this._runTask(task);
  92623. }
  92624. return this;
  92625. };
  92626. return AssetsManager;
  92627. }());
  92628. BABYLON.AssetsManager = AssetsManager;
  92629. })(BABYLON || (BABYLON = {}));
  92630. //# sourceMappingURL=babylon.assetsManager.js.map
  92631. var BABYLON;
  92632. (function (BABYLON) {
  92633. var serializedGeometries = [];
  92634. var serializeGeometry = function (geometry, serializationGeometries) {
  92635. if (serializedGeometries[geometry.id]) {
  92636. return;
  92637. }
  92638. if (geometry.doNotSerialize) {
  92639. return;
  92640. }
  92641. if (geometry instanceof BABYLON.BoxGeometry) {
  92642. serializationGeometries.boxes.push(geometry.serialize());
  92643. }
  92644. else if (geometry instanceof BABYLON.SphereGeometry) {
  92645. serializationGeometries.spheres.push(geometry.serialize());
  92646. }
  92647. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92648. serializationGeometries.cylinders.push(geometry.serialize());
  92649. }
  92650. else if (geometry instanceof BABYLON.TorusGeometry) {
  92651. serializationGeometries.toruses.push(geometry.serialize());
  92652. }
  92653. else if (geometry instanceof BABYLON.GroundGeometry) {
  92654. serializationGeometries.grounds.push(geometry.serialize());
  92655. }
  92656. else if (geometry instanceof BABYLON.Plane) {
  92657. serializationGeometries.planes.push(geometry.serialize());
  92658. }
  92659. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92660. serializationGeometries.torusKnots.push(geometry.serialize());
  92661. }
  92662. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92663. throw new Error("Unknown primitive type");
  92664. }
  92665. else {
  92666. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92667. }
  92668. serializedGeometries[geometry.id] = true;
  92669. };
  92670. var serializeMesh = function (mesh, serializationScene) {
  92671. var serializationObject = {};
  92672. // Geometry
  92673. var geometry = mesh._geometry;
  92674. if (geometry) {
  92675. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92676. // 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
  92677. serializeGeometry(geometry, serializationScene.geometries);
  92678. }
  92679. }
  92680. // Custom
  92681. if (mesh.serialize) {
  92682. mesh.serialize(serializationObject);
  92683. }
  92684. return serializationObject;
  92685. };
  92686. var finalizeSingleMesh = function (mesh, serializationObject) {
  92687. //only works if the mesh is already loaded
  92688. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92689. //serialize material
  92690. if (mesh.material) {
  92691. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92692. serializationObject.materials = serializationObject.materials || [];
  92693. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92694. serializationObject.materials.push(mesh.material.serialize());
  92695. }
  92696. }
  92697. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92698. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92699. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92700. serializationObject.multiMaterials.push(mesh.material.serialize());
  92701. }
  92702. }
  92703. }
  92704. //serialize geometry
  92705. var geometry = mesh._geometry;
  92706. if (geometry) {
  92707. if (!serializationObject.geometries) {
  92708. serializationObject.geometries = {};
  92709. serializationObject.geometries.boxes = [];
  92710. serializationObject.geometries.spheres = [];
  92711. serializationObject.geometries.cylinders = [];
  92712. serializationObject.geometries.toruses = [];
  92713. serializationObject.geometries.grounds = [];
  92714. serializationObject.geometries.planes = [];
  92715. serializationObject.geometries.torusKnots = [];
  92716. serializationObject.geometries.vertexData = [];
  92717. }
  92718. serializeGeometry(geometry, serializationObject.geometries);
  92719. }
  92720. // Skeletons
  92721. if (mesh.skeleton) {
  92722. serializationObject.skeletons = serializationObject.skeletons || [];
  92723. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92724. }
  92725. //serialize the actual mesh
  92726. serializationObject.meshes = serializationObject.meshes || [];
  92727. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92728. }
  92729. };
  92730. var SceneSerializer = /** @class */ (function () {
  92731. function SceneSerializer() {
  92732. }
  92733. SceneSerializer.ClearCache = function () {
  92734. serializedGeometries = [];
  92735. };
  92736. SceneSerializer.Serialize = function (scene) {
  92737. var serializationObject = {};
  92738. SceneSerializer.ClearCache();
  92739. // Scene
  92740. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92741. serializationObject.autoClear = scene.autoClear;
  92742. serializationObject.clearColor = scene.clearColor.asArray();
  92743. serializationObject.ambientColor = scene.ambientColor.asArray();
  92744. serializationObject.gravity = scene.gravity.asArray();
  92745. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92746. serializationObject.workerCollisions = scene.workerCollisions;
  92747. // Fog
  92748. if (scene.fogMode && scene.fogMode !== 0) {
  92749. serializationObject.fogMode = scene.fogMode;
  92750. serializationObject.fogColor = scene.fogColor.asArray();
  92751. serializationObject.fogStart = scene.fogStart;
  92752. serializationObject.fogEnd = scene.fogEnd;
  92753. serializationObject.fogDensity = scene.fogDensity;
  92754. }
  92755. //Physics
  92756. if (scene.isPhysicsEnabled()) {
  92757. var physicEngine = scene.getPhysicsEngine();
  92758. if (physicEngine) {
  92759. serializationObject.physicsEnabled = true;
  92760. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92761. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92762. }
  92763. }
  92764. // Metadata
  92765. if (scene.metadata) {
  92766. serializationObject.metadata = scene.metadata;
  92767. }
  92768. // Morph targets
  92769. serializationObject.morphTargetManagers = [];
  92770. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92771. var abstractMesh = _a[_i];
  92772. var manager = abstractMesh.morphTargetManager;
  92773. if (manager) {
  92774. serializationObject.morphTargetManagers.push(manager.serialize());
  92775. }
  92776. }
  92777. // Lights
  92778. serializationObject.lights = [];
  92779. var index;
  92780. var light;
  92781. for (index = 0; index < scene.lights.length; index++) {
  92782. light = scene.lights[index];
  92783. if (!light.doNotSerialize) {
  92784. serializationObject.lights.push(light.serialize());
  92785. }
  92786. }
  92787. // Cameras
  92788. serializationObject.cameras = [];
  92789. for (index = 0; index < scene.cameras.length; index++) {
  92790. var camera = scene.cameras[index];
  92791. if (!camera.doNotSerialize) {
  92792. serializationObject.cameras.push(camera.serialize());
  92793. }
  92794. }
  92795. if (scene.activeCamera) {
  92796. serializationObject.activeCameraID = scene.activeCamera.id;
  92797. }
  92798. // Animations
  92799. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92800. // Materials
  92801. serializationObject.materials = [];
  92802. serializationObject.multiMaterials = [];
  92803. var material;
  92804. for (index = 0; index < scene.materials.length; index++) {
  92805. material = scene.materials[index];
  92806. if (!material.doNotSerialize) {
  92807. serializationObject.materials.push(material.serialize());
  92808. }
  92809. }
  92810. // MultiMaterials
  92811. serializationObject.multiMaterials = [];
  92812. for (index = 0; index < scene.multiMaterials.length; index++) {
  92813. var multiMaterial = scene.multiMaterials[index];
  92814. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92815. }
  92816. // Environment texture
  92817. if (scene.environmentTexture) {
  92818. serializationObject.environmentTexture = scene.environmentTexture.name;
  92819. }
  92820. // Skeletons
  92821. serializationObject.skeletons = [];
  92822. for (index = 0; index < scene.skeletons.length; index++) {
  92823. var skeleton = scene.skeletons[index];
  92824. if (!skeleton.doNotSerialize) {
  92825. serializationObject.skeletons.push(skeleton.serialize());
  92826. }
  92827. }
  92828. // Transform nodes
  92829. serializationObject.transformNodes = [];
  92830. for (index = 0; index < scene.transformNodes.length; index++) {
  92831. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92832. }
  92833. // Geometries
  92834. serializationObject.geometries = {};
  92835. serializationObject.geometries.boxes = [];
  92836. serializationObject.geometries.spheres = [];
  92837. serializationObject.geometries.cylinders = [];
  92838. serializationObject.geometries.toruses = [];
  92839. serializationObject.geometries.grounds = [];
  92840. serializationObject.geometries.planes = [];
  92841. serializationObject.geometries.torusKnots = [];
  92842. serializationObject.geometries.vertexData = [];
  92843. serializedGeometries = [];
  92844. var geometries = scene.getGeometries();
  92845. for (index = 0; index < geometries.length; index++) {
  92846. var geometry = geometries[index];
  92847. if (geometry.isReady()) {
  92848. serializeGeometry(geometry, serializationObject.geometries);
  92849. }
  92850. }
  92851. // Meshes
  92852. serializationObject.meshes = [];
  92853. for (index = 0; index < scene.meshes.length; index++) {
  92854. var abstractMesh = scene.meshes[index];
  92855. if (abstractMesh instanceof BABYLON.Mesh) {
  92856. var mesh = abstractMesh;
  92857. if (!mesh.doNotSerialize) {
  92858. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92859. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92860. }
  92861. }
  92862. }
  92863. }
  92864. // Particles Systems
  92865. serializationObject.particleSystems = [];
  92866. for (index = 0; index < scene.particleSystems.length; index++) {
  92867. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92868. }
  92869. // Lens flares
  92870. serializationObject.lensFlareSystems = [];
  92871. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92872. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92873. }
  92874. // Shadows
  92875. serializationObject.shadowGenerators = [];
  92876. for (index = 0; index < scene.lights.length; index++) {
  92877. light = scene.lights[index];
  92878. var shadowGenerator = light.getShadowGenerator();
  92879. if (shadowGenerator) {
  92880. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92881. }
  92882. }
  92883. // Action Manager
  92884. if (scene.actionManager) {
  92885. serializationObject.actions = scene.actionManager.serialize("scene");
  92886. }
  92887. // Audio
  92888. serializationObject.sounds = [];
  92889. for (index = 0; index < scene.soundTracks.length; index++) {
  92890. var soundtrack = scene.soundTracks[index];
  92891. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  92892. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92893. }
  92894. }
  92895. // Effect layers
  92896. serializationObject.effectLayers = [];
  92897. for (index = 0; index < scene.effectLayers.length; index++) {
  92898. var layer = scene.effectLayers[index];
  92899. if (layer.serialize) {
  92900. serializationObject.effectLayers.push(layer.serialize());
  92901. }
  92902. }
  92903. return serializationObject;
  92904. };
  92905. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92906. if (withParents === void 0) { withParents = false; }
  92907. if (withChildren === void 0) { withChildren = false; }
  92908. var serializationObject = {};
  92909. SceneSerializer.ClearCache();
  92910. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92911. if (withParents || withChildren) {
  92912. //deliberate for loop! not for each, appended should be processed as well.
  92913. for (var i = 0; i < toSerialize.length; ++i) {
  92914. if (withChildren) {
  92915. toSerialize[i].getDescendants().forEach(function (node) {
  92916. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92917. toSerialize.push(node);
  92918. }
  92919. });
  92920. }
  92921. //make sure the array doesn't contain the object already
  92922. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92923. toSerialize.push(toSerialize[i].parent);
  92924. }
  92925. }
  92926. }
  92927. toSerialize.forEach(function (mesh) {
  92928. finalizeSingleMesh(mesh, serializationObject);
  92929. });
  92930. return serializationObject;
  92931. };
  92932. return SceneSerializer;
  92933. }());
  92934. BABYLON.SceneSerializer = SceneSerializer;
  92935. })(BABYLON || (BABYLON = {}));
  92936. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92937. var BABYLON;
  92938. (function (BABYLON) {
  92939. var ReflectionProbe = /** @class */ (function () {
  92940. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92942. var _this = this;
  92943. this.name = name;
  92944. this._viewMatrix = BABYLON.Matrix.Identity();
  92945. this._target = BABYLON.Vector3.Zero();
  92946. this._add = BABYLON.Vector3.Zero();
  92947. this._invertYAxis = false;
  92948. this.position = BABYLON.Vector3.Zero();
  92949. this._scene = scene;
  92950. this._scene.reflectionProbes.push(this);
  92951. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92952. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92953. switch (faceIndex) {
  92954. case 0:
  92955. _this._add.copyFromFloats(1, 0, 0);
  92956. break;
  92957. case 1:
  92958. _this._add.copyFromFloats(-1, 0, 0);
  92959. break;
  92960. case 2:
  92961. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92962. break;
  92963. case 3:
  92964. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92965. break;
  92966. case 4:
  92967. _this._add.copyFromFloats(0, 0, 1);
  92968. break;
  92969. case 5:
  92970. _this._add.copyFromFloats(0, 0, -1);
  92971. break;
  92972. }
  92973. if (_this._attachedMesh) {
  92974. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92975. }
  92976. _this.position.addToRef(_this._add, _this._target);
  92977. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92978. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92979. scene._forcedViewPosition = _this.position;
  92980. });
  92981. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92982. scene._forcedViewPosition = null;
  92983. scene.updateTransformMatrix(true);
  92984. });
  92985. if (scene.activeCamera) {
  92986. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92987. }
  92988. }
  92989. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92990. get: function () {
  92991. return this._renderTargetTexture.samples;
  92992. },
  92993. set: function (value) {
  92994. this._renderTargetTexture.samples = value;
  92995. },
  92996. enumerable: true,
  92997. configurable: true
  92998. });
  92999. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93000. get: function () {
  93001. return this._renderTargetTexture.refreshRate;
  93002. },
  93003. set: function (value) {
  93004. this._renderTargetTexture.refreshRate = value;
  93005. },
  93006. enumerable: true,
  93007. configurable: true
  93008. });
  93009. ReflectionProbe.prototype.getScene = function () {
  93010. return this._scene;
  93011. };
  93012. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93013. get: function () {
  93014. return this._renderTargetTexture;
  93015. },
  93016. enumerable: true,
  93017. configurable: true
  93018. });
  93019. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93020. get: function () {
  93021. return this._renderTargetTexture.renderList;
  93022. },
  93023. enumerable: true,
  93024. configurable: true
  93025. });
  93026. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93027. this._attachedMesh = mesh;
  93028. };
  93029. /**
  93030. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93031. *
  93032. * @param renderingGroupId The rendering group id corresponding to its index
  93033. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93034. */
  93035. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93036. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93037. };
  93038. ReflectionProbe.prototype.dispose = function () {
  93039. var index = this._scene.reflectionProbes.indexOf(this);
  93040. if (index !== -1) {
  93041. // Remove from the scene if found
  93042. this._scene.reflectionProbes.splice(index, 1);
  93043. }
  93044. if (this._renderTargetTexture) {
  93045. this._renderTargetTexture.dispose();
  93046. this._renderTargetTexture = null;
  93047. }
  93048. };
  93049. return ReflectionProbe;
  93050. }());
  93051. BABYLON.ReflectionProbe = ReflectionProbe;
  93052. })(BABYLON || (BABYLON = {}));
  93053. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93054. var BABYLON;
  93055. (function (BABYLON) {
  93056. var Layer = /** @class */ (function () {
  93057. function Layer(name, imgUrl, scene, isBackground, color) {
  93058. this.name = name;
  93059. this.scale = new BABYLON.Vector2(1, 1);
  93060. this.offset = new BABYLON.Vector2(0, 0);
  93061. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93062. this.layerMask = 0x0FFFFFFF;
  93063. this._vertexBuffers = {};
  93064. // Events
  93065. /**
  93066. * An event triggered when the layer is disposed.
  93067. */
  93068. this.onDisposeObservable = new BABYLON.Observable();
  93069. /**
  93070. * An event triggered before rendering the scene
  93071. */
  93072. this.onBeforeRenderObservable = new BABYLON.Observable();
  93073. /**
  93074. * An event triggered after rendering the scene
  93075. */
  93076. this.onAfterRenderObservable = new BABYLON.Observable();
  93077. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93078. this.isBackground = isBackground === undefined ? true : isBackground;
  93079. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93080. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93081. this._scene.layers.push(this);
  93082. var engine = this._scene.getEngine();
  93083. // VBO
  93084. var vertices = [];
  93085. vertices.push(1, 1);
  93086. vertices.push(-1, 1);
  93087. vertices.push(-1, -1);
  93088. vertices.push(1, -1);
  93089. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93090. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93091. this._createIndexBuffer();
  93092. // Effects
  93093. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93094. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93095. }
  93096. Object.defineProperty(Layer.prototype, "onDispose", {
  93097. set: function (callback) {
  93098. if (this._onDisposeObserver) {
  93099. this.onDisposeObservable.remove(this._onDisposeObserver);
  93100. }
  93101. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93102. },
  93103. enumerable: true,
  93104. configurable: true
  93105. });
  93106. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93107. set: function (callback) {
  93108. if (this._onBeforeRenderObserver) {
  93109. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93110. }
  93111. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93112. },
  93113. enumerable: true,
  93114. configurable: true
  93115. });
  93116. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93117. set: function (callback) {
  93118. if (this._onAfterRenderObserver) {
  93119. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93120. }
  93121. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93122. },
  93123. enumerable: true,
  93124. configurable: true
  93125. });
  93126. Layer.prototype._createIndexBuffer = function () {
  93127. var engine = this._scene.getEngine();
  93128. // Indices
  93129. var indices = [];
  93130. indices.push(0);
  93131. indices.push(1);
  93132. indices.push(2);
  93133. indices.push(0);
  93134. indices.push(2);
  93135. indices.push(3);
  93136. this._indexBuffer = engine.createIndexBuffer(indices);
  93137. };
  93138. Layer.prototype._rebuild = function () {
  93139. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93140. if (vb) {
  93141. vb._rebuild();
  93142. }
  93143. this._createIndexBuffer();
  93144. };
  93145. Layer.prototype.render = function () {
  93146. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93147. // Check
  93148. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93149. return;
  93150. var engine = this._scene.getEngine();
  93151. this.onBeforeRenderObservable.notifyObservers(this);
  93152. // Render
  93153. engine.enableEffect(currentEffect);
  93154. engine.setState(false);
  93155. // Texture
  93156. currentEffect.setTexture("textureSampler", this.texture);
  93157. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93158. // Color
  93159. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93160. // Scale / offset
  93161. currentEffect.setVector2("offset", this.offset);
  93162. currentEffect.setVector2("scale", this.scale);
  93163. // VBOs
  93164. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93165. // Draw order
  93166. if (!this.alphaTest) {
  93167. engine.setAlphaMode(this.alphaBlendingMode);
  93168. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93169. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93170. }
  93171. else {
  93172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93173. }
  93174. this.onAfterRenderObservable.notifyObservers(this);
  93175. };
  93176. Layer.prototype.dispose = function () {
  93177. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93178. if (vertexBuffer) {
  93179. vertexBuffer.dispose();
  93180. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93181. }
  93182. if (this._indexBuffer) {
  93183. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93184. this._indexBuffer = null;
  93185. }
  93186. if (this.texture) {
  93187. this.texture.dispose();
  93188. this.texture = null;
  93189. }
  93190. // Remove from scene
  93191. var index = this._scene.layers.indexOf(this);
  93192. this._scene.layers.splice(index, 1);
  93193. // Callback
  93194. this.onDisposeObservable.notifyObservers(this);
  93195. this.onDisposeObservable.clear();
  93196. this.onAfterRenderObservable.clear();
  93197. this.onBeforeRenderObservable.clear();
  93198. };
  93199. return Layer;
  93200. }());
  93201. BABYLON.Layer = Layer;
  93202. })(BABYLON || (BABYLON = {}));
  93203. //# sourceMappingURL=babylon.layer.js.map
  93204. var BABYLON;
  93205. (function (BABYLON) {
  93206. var TextureTools = /** @class */ (function () {
  93207. function TextureTools() {
  93208. }
  93209. /**
  93210. * Uses the GPU to create a copy texture rescaled at a given size
  93211. * @param texture Texture to copy from
  93212. * @param width Desired width
  93213. * @param height Desired height
  93214. * @return Generated texture
  93215. */
  93216. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93217. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93218. var scene = texture.getScene();
  93219. var engine = scene.getEngine();
  93220. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93221. rtt.wrapU = texture.wrapU;
  93222. rtt.wrapV = texture.wrapV;
  93223. rtt.uOffset = texture.uOffset;
  93224. rtt.vOffset = texture.vOffset;
  93225. rtt.uScale = texture.uScale;
  93226. rtt.vScale = texture.vScale;
  93227. rtt.uAng = texture.uAng;
  93228. rtt.vAng = texture.vAng;
  93229. rtt.wAng = texture.wAng;
  93230. rtt.coordinatesIndex = texture.coordinatesIndex;
  93231. rtt.level = texture.level;
  93232. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93233. rtt._texture.isReady = false;
  93234. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93235. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93236. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93237. passPostProcess.getEffect().executeWhenCompiled(function () {
  93238. passPostProcess.onApply = function (effect) {
  93239. effect.setTexture("textureSampler", texture);
  93240. };
  93241. var internalTexture = rtt.getInternalTexture();
  93242. if (internalTexture) {
  93243. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93244. engine.unBindFramebuffer(internalTexture);
  93245. rtt.disposeFramebufferObjects();
  93246. passPostProcess.dispose();
  93247. internalTexture.isReady = true;
  93248. }
  93249. });
  93250. return rtt;
  93251. };
  93252. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93253. if (!scene._environmentBRDFTexture) {
  93254. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93255. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93256. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93257. scene._environmentBRDFTexture = texture;
  93258. }
  93259. return scene._environmentBRDFTexture;
  93260. };
  93261. 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=";
  93262. return TextureTools;
  93263. }());
  93264. BABYLON.TextureTools = TextureTools;
  93265. })(BABYLON || (BABYLON = {}));
  93266. //# sourceMappingURL=babylon.textureTools.js.map
  93267. var BABYLON;
  93268. (function (BABYLON) {
  93269. var FramingBehavior = /** @class */ (function () {
  93270. function FramingBehavior() {
  93271. this._mode = FramingBehavior.FitFrustumSidesMode;
  93272. this._radiusScale = 1.0;
  93273. this._positionScale = 0.5;
  93274. this._defaultElevation = 0.3;
  93275. this._elevationReturnTime = 1500;
  93276. this._elevationReturnWaitTime = 1000;
  93277. this._zoomStopsAnimation = false;
  93278. this._framingTime = 1500;
  93279. this._isPointerDown = false;
  93280. this._lastInteractionTime = -Infinity;
  93281. // Framing control
  93282. this._animatables = new Array();
  93283. this._betaIsAnimating = false;
  93284. }
  93285. Object.defineProperty(FramingBehavior.prototype, "name", {
  93286. get: function () {
  93287. return "Framing";
  93288. },
  93289. enumerable: true,
  93290. configurable: true
  93291. });
  93292. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93293. /**
  93294. * Gets current mode used by the behavior.
  93295. */
  93296. get: function () {
  93297. return this._mode;
  93298. },
  93299. /**
  93300. * Sets the current mode used by the behavior
  93301. */
  93302. set: function (mode) {
  93303. this._mode = mode;
  93304. },
  93305. enumerable: true,
  93306. configurable: true
  93307. });
  93308. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93309. /**
  93310. * Gets the scale applied to the radius
  93311. */
  93312. get: function () {
  93313. return this._radiusScale;
  93314. },
  93315. /**
  93316. * Sets the scale applied to the radius (1 by default)
  93317. */
  93318. set: function (radius) {
  93319. this._radiusScale = radius;
  93320. },
  93321. enumerable: true,
  93322. configurable: true
  93323. });
  93324. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93325. /**
  93326. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93327. */
  93328. get: function () {
  93329. return this._positionScale;
  93330. },
  93331. /**
  93332. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93333. */
  93334. set: function (scale) {
  93335. this._positionScale = scale;
  93336. },
  93337. enumerable: true,
  93338. configurable: true
  93339. });
  93340. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93341. /**
  93342. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93343. * behaviour is triggered, in radians.
  93344. */
  93345. get: function () {
  93346. return this._defaultElevation;
  93347. },
  93348. /**
  93349. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93350. * behaviour is triggered, in radians.
  93351. */
  93352. set: function (elevation) {
  93353. this._defaultElevation = elevation;
  93354. },
  93355. enumerable: true,
  93356. configurable: true
  93357. });
  93358. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93359. /**
  93360. * Gets the time (in milliseconds) taken to return to the default beta position.
  93361. * Negative value indicates camera should not return to default.
  93362. */
  93363. get: function () {
  93364. return this._elevationReturnTime;
  93365. },
  93366. /**
  93367. * Sets the time (in milliseconds) taken to return to the default beta position.
  93368. * Negative value indicates camera should not return to default.
  93369. */
  93370. set: function (speed) {
  93371. this._elevationReturnTime = speed;
  93372. },
  93373. enumerable: true,
  93374. configurable: true
  93375. });
  93376. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  93377. /**
  93378. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93379. */
  93380. get: function () {
  93381. return this._elevationReturnWaitTime;
  93382. },
  93383. /**
  93384. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93385. */
  93386. set: function (time) {
  93387. this._elevationReturnWaitTime = time;
  93388. },
  93389. enumerable: true,
  93390. configurable: true
  93391. });
  93392. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  93393. /**
  93394. * Gets the flag that indicates if user zooming should stop animation.
  93395. */
  93396. get: function () {
  93397. return this._zoomStopsAnimation;
  93398. },
  93399. /**
  93400. * Sets the flag that indicates if user zooming should stop animation.
  93401. */
  93402. set: function (flag) {
  93403. this._zoomStopsAnimation = flag;
  93404. },
  93405. enumerable: true,
  93406. configurable: true
  93407. });
  93408. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  93409. /**
  93410. * Gets the transition time when framing the mesh, in milliseconds
  93411. */
  93412. get: function () {
  93413. return this._framingTime;
  93414. },
  93415. /**
  93416. * Sets the transition time when framing the mesh, in milliseconds
  93417. */
  93418. set: function (time) {
  93419. this._framingTime = time;
  93420. },
  93421. enumerable: true,
  93422. configurable: true
  93423. });
  93424. FramingBehavior.prototype.init = function () {
  93425. // Do notihng
  93426. };
  93427. FramingBehavior.prototype.attach = function (camera) {
  93428. var _this = this;
  93429. this._attachedCamera = camera;
  93430. var scene = this._attachedCamera.getScene();
  93431. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  93432. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93433. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93434. _this._isPointerDown = true;
  93435. return;
  93436. }
  93437. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93438. _this._isPointerDown = false;
  93439. }
  93440. });
  93441. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93442. if (mesh) {
  93443. _this.zoomOnMesh(mesh);
  93444. }
  93445. });
  93446. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93447. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93448. _this._applyUserInteraction();
  93449. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  93450. // back to the default position after a given timeout
  93451. _this._maintainCameraAboveGround();
  93452. });
  93453. };
  93454. FramingBehavior.prototype.detach = function () {
  93455. if (!this._attachedCamera) {
  93456. return;
  93457. }
  93458. var scene = this._attachedCamera.getScene();
  93459. if (this._onPrePointerObservableObserver) {
  93460. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93461. }
  93462. if (this._onAfterCheckInputsObserver) {
  93463. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93464. }
  93465. if (this._onMeshTargetChangedObserver) {
  93466. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93467. }
  93468. this._attachedCamera = null;
  93469. };
  93470. /**
  93471. * Targets the given mesh and updates zoom level accordingly.
  93472. * @param mesh The mesh to target.
  93473. * @param radius Optional. If a cached radius position already exists, overrides default.
  93474. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93475. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93476. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93477. */
  93478. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93479. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93480. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93481. mesh.computeWorldMatrix(true);
  93482. var boundingBox = mesh.getBoundingInfo().boundingBox;
  93483. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  93484. };
  93485. /**
  93486. * Targets the given mesh with its children and updates zoom level accordingly.
  93487. * @param mesh The mesh to target.
  93488. * @param radius Optional. If a cached radius position already exists, overrides default.
  93489. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93490. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93491. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93492. */
  93493. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93494. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93495. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93496. mesh.computeWorldMatrix(true);
  93497. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  93498. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  93499. };
  93500. /**
  93501. * Targets the given meshes with their children and updates zoom level accordingly.
  93502. * @param meshes The mesh to target.
  93503. * @param radius Optional. If a cached radius position already exists, overrides default.
  93504. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93505. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93506. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93507. */
  93508. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  93509. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93510. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93511. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  93512. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  93513. for (var i = 0; i < meshes.length; i++) {
  93514. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  93515. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  93516. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  93517. }
  93518. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  93519. };
  93520. /**
  93521. * Targets the given mesh and updates zoom level accordingly.
  93522. * @param mesh The mesh to target.
  93523. * @param radius Optional. If a cached radius position already exists, overrides default.
  93524. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93525. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93526. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93527. */
  93528. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  93529. var _this = this;
  93530. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93531. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93532. var zoomTarget;
  93533. if (!this._attachedCamera) {
  93534. return;
  93535. }
  93536. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  93537. var bottom = minimumWorld.y;
  93538. var top = maximumWorld.y;
  93539. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  93540. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  93541. if (focusOnOriginXZ) {
  93542. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  93543. }
  93544. else {
  93545. var centerWorld = minimumWorld.add(radiusWorld);
  93546. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  93547. }
  93548. if (!this._vectorTransition) {
  93549. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  93550. }
  93551. this._betaIsAnimating = true;
  93552. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  93553. if (animatable) {
  93554. this._animatables.push(animatable);
  93555. }
  93556. // sets the radius and lower radius bounds
  93557. // Small delta ensures camera is not always at lower zoom limit.
  93558. var radius = 0;
  93559. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  93560. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93561. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  93562. radius = position;
  93563. }
  93564. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93565. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93566. if (this._attachedCamera.lowerRadiusLimit === null) {
  93567. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  93568. }
  93569. }
  93570. // Set sensibilities
  93571. var extend = maximumWorld.subtract(minimumWorld).length();
  93572. this._attachedCamera.panningSensibility = 5000 / extend;
  93573. this._attachedCamera.wheelPrecision = 100 / radius;
  93574. // transition to new radius
  93575. if (!this._radiusTransition) {
  93576. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93577. }
  93578. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  93579. _this.stopAllAnimations();
  93580. if (onAnimationEnd) {
  93581. onAnimationEnd();
  93582. }
  93583. if (_this._attachedCamera) {
  93584. _this._attachedCamera.storeState();
  93585. }
  93586. });
  93587. if (animatable) {
  93588. this._animatables.push(animatable);
  93589. }
  93590. };
  93591. /**
  93592. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93593. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93594. * frustum width.
  93595. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93596. * to fully enclose the mesh in the viewing frustum.
  93597. */
  93598. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93599. var size = maximumWorld.subtract(minimumWorld);
  93600. var boxVectorGlobalDiagonal = size.length();
  93601. var frustumSlope = this._getFrustumSlope();
  93602. // Formula for setting distance
  93603. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93604. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93605. // Horizon distance
  93606. var radius = radiusWithoutFraming * this._radiusScale;
  93607. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93608. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93609. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93610. var camera = this._attachedCamera;
  93611. if (!camera) {
  93612. return 0;
  93613. }
  93614. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93615. // Don't exceed the requested limit
  93616. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93617. }
  93618. // Don't exceed the upper radius limit
  93619. if (camera.upperRadiusLimit) {
  93620. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93621. }
  93622. return distance;
  93623. };
  93624. /**
  93625. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93626. * is automatically returned to its default position (expected to be above ground plane).
  93627. */
  93628. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93629. var _this = this;
  93630. if (this._elevationReturnTime < 0) {
  93631. return;
  93632. }
  93633. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93634. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93635. var limitBeta = Math.PI * 0.5;
  93636. // Bring the camera back up if below the ground plane
  93637. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93638. this._betaIsAnimating = true;
  93639. //Transition to new position
  93640. this.stopAllAnimations();
  93641. if (!this._betaTransition) {
  93642. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93643. }
  93644. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93645. _this._clearAnimationLocks();
  93646. _this.stopAllAnimations();
  93647. });
  93648. if (animatabe) {
  93649. this._animatables.push(animatabe);
  93650. }
  93651. }
  93652. };
  93653. /**
  93654. * Returns the frustum slope based on the canvas ratio and camera FOV
  93655. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93656. */
  93657. FramingBehavior.prototype._getFrustumSlope = function () {
  93658. // Calculate the viewport ratio
  93659. // Aspect Ratio is Height/Width.
  93660. var camera = this._attachedCamera;
  93661. if (!camera) {
  93662. return BABYLON.Vector2.Zero();
  93663. }
  93664. var engine = camera.getScene().getEngine();
  93665. var aspectRatio = engine.getAspectRatio(camera);
  93666. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93667. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93668. var frustumSlopeY = Math.tan(camera.fov / 2);
  93669. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93670. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93671. // along the forward vector.
  93672. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93673. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93674. };
  93675. /**
  93676. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93677. */
  93678. FramingBehavior.prototype._clearAnimationLocks = function () {
  93679. this._betaIsAnimating = false;
  93680. };
  93681. /**
  93682. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93683. */
  93684. FramingBehavior.prototype._applyUserInteraction = function () {
  93685. if (this.isUserIsMoving) {
  93686. this._lastInteractionTime = BABYLON.Tools.Now;
  93687. this.stopAllAnimations();
  93688. this._clearAnimationLocks();
  93689. }
  93690. };
  93691. /**
  93692. * Stops and removes all animations that have been applied to the camera
  93693. */
  93694. FramingBehavior.prototype.stopAllAnimations = function () {
  93695. if (this._attachedCamera) {
  93696. this._attachedCamera.animations = [];
  93697. }
  93698. while (this._animatables.length) {
  93699. if (this._animatables[0]) {
  93700. this._animatables[0].onAnimationEnd = null;
  93701. this._animatables[0].stop();
  93702. }
  93703. this._animatables.shift();
  93704. }
  93705. };
  93706. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93707. /**
  93708. * Gets a value indicating if the user is moving the camera
  93709. */
  93710. get: function () {
  93711. if (!this._attachedCamera) {
  93712. return false;
  93713. }
  93714. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93715. this._attachedCamera.inertialBetaOffset !== 0 ||
  93716. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93717. this._attachedCamera.inertialPanningX !== 0 ||
  93718. this._attachedCamera.inertialPanningY !== 0 ||
  93719. this._isPointerDown;
  93720. },
  93721. enumerable: true,
  93722. configurable: true
  93723. });
  93724. /**
  93725. * The easing function used by animations
  93726. */
  93727. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93728. /**
  93729. * The easing mode used by animations
  93730. */
  93731. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93732. // Statics
  93733. /**
  93734. * The camera can move all the way towards the mesh.
  93735. */
  93736. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93737. /**
  93738. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93739. */
  93740. FramingBehavior.FitFrustumSidesMode = 1;
  93741. return FramingBehavior;
  93742. }());
  93743. BABYLON.FramingBehavior = FramingBehavior;
  93744. })(BABYLON || (BABYLON = {}));
  93745. //# sourceMappingURL=babylon.framingBehavior.js.map
  93746. var BABYLON;
  93747. (function (BABYLON) {
  93748. /**
  93749. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93750. */
  93751. var BouncingBehavior = /** @class */ (function () {
  93752. function BouncingBehavior() {
  93753. /**
  93754. * The duration of the animation, in milliseconds
  93755. */
  93756. this.transitionDuration = 450;
  93757. /**
  93758. * Length of the distance animated by the transition when lower radius is reached
  93759. */
  93760. this.lowerRadiusTransitionRange = 2;
  93761. /**
  93762. * Length of the distance animated by the transition when upper radius is reached
  93763. */
  93764. this.upperRadiusTransitionRange = -2;
  93765. this._autoTransitionRange = false;
  93766. // Animations
  93767. this._radiusIsAnimating = false;
  93768. this._radiusBounceTransition = null;
  93769. this._animatables = new Array();
  93770. }
  93771. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93772. get: function () {
  93773. return "Bouncing";
  93774. },
  93775. enumerable: true,
  93776. configurable: true
  93777. });
  93778. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93779. /**
  93780. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93781. */
  93782. get: function () {
  93783. return this._autoTransitionRange;
  93784. },
  93785. /**
  93786. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93787. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93788. */
  93789. set: function (value) {
  93790. var _this = this;
  93791. if (this._autoTransitionRange === value) {
  93792. return;
  93793. }
  93794. this._autoTransitionRange = value;
  93795. var camera = this._attachedCamera;
  93796. if (!camera) {
  93797. return;
  93798. }
  93799. if (value) {
  93800. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93801. if (!mesh) {
  93802. return;
  93803. }
  93804. mesh.computeWorldMatrix(true);
  93805. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93806. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93807. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93808. });
  93809. }
  93810. else if (this._onMeshTargetChangedObserver) {
  93811. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93812. }
  93813. },
  93814. enumerable: true,
  93815. configurable: true
  93816. });
  93817. BouncingBehavior.prototype.init = function () {
  93818. // Do notihng
  93819. };
  93820. BouncingBehavior.prototype.attach = function (camera) {
  93821. var _this = this;
  93822. this._attachedCamera = camera;
  93823. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93824. if (!_this._attachedCamera) {
  93825. return;
  93826. }
  93827. // Add the bounce animation to the lower radius limit
  93828. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93829. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93830. }
  93831. // Add the bounce animation to the upper radius limit
  93832. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93833. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93834. }
  93835. });
  93836. };
  93837. BouncingBehavior.prototype.detach = function () {
  93838. if (!this._attachedCamera) {
  93839. return;
  93840. }
  93841. if (this._onAfterCheckInputsObserver) {
  93842. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93843. }
  93844. if (this._onMeshTargetChangedObserver) {
  93845. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93846. }
  93847. this._attachedCamera = null;
  93848. };
  93849. /**
  93850. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93851. * @param radiusLimit The limit to check against.
  93852. * @return Bool to indicate if at limit.
  93853. */
  93854. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93855. if (!this._attachedCamera) {
  93856. return false;
  93857. }
  93858. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93859. return true;
  93860. }
  93861. return false;
  93862. };
  93863. /**
  93864. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93865. * @param radiusDelta The delta by which to animate to. Can be negative.
  93866. */
  93867. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93868. var _this = this;
  93869. if (!this._attachedCamera) {
  93870. return;
  93871. }
  93872. if (!this._radiusBounceTransition) {
  93873. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93874. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93875. }
  93876. // Prevent zoom until bounce has completed
  93877. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93878. this._attachedCamera.wheelPrecision = Infinity;
  93879. this._attachedCamera.inertialRadiusOffset = 0;
  93880. // Animate to the radius limit
  93881. this.stopAllAnimations();
  93882. this._radiusIsAnimating = true;
  93883. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93884. if (animatable) {
  93885. this._animatables.push(animatable);
  93886. }
  93887. };
  93888. /**
  93889. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93890. */
  93891. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93892. this._radiusIsAnimating = false;
  93893. if (this._attachedCamera) {
  93894. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93895. }
  93896. };
  93897. /**
  93898. * Stops and removes all animations that have been applied to the camera
  93899. */
  93900. BouncingBehavior.prototype.stopAllAnimations = function () {
  93901. if (this._attachedCamera) {
  93902. this._attachedCamera.animations = [];
  93903. }
  93904. while (this._animatables.length) {
  93905. this._animatables[0].onAnimationEnd = null;
  93906. this._animatables[0].stop();
  93907. this._animatables.shift();
  93908. }
  93909. };
  93910. /**
  93911. * The easing function used by animations
  93912. */
  93913. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93914. /**
  93915. * The easing mode used by animations
  93916. */
  93917. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93918. return BouncingBehavior;
  93919. }());
  93920. BABYLON.BouncingBehavior = BouncingBehavior;
  93921. })(BABYLON || (BABYLON = {}));
  93922. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93923. var BABYLON;
  93924. (function (BABYLON) {
  93925. var AutoRotationBehavior = /** @class */ (function () {
  93926. function AutoRotationBehavior() {
  93927. this._zoomStopsAnimation = false;
  93928. this._idleRotationSpeed = 0.05;
  93929. this._idleRotationWaitTime = 2000;
  93930. this._idleRotationSpinupTime = 2000;
  93931. this._isPointerDown = false;
  93932. this._lastFrameTime = null;
  93933. this._lastInteractionTime = -Infinity;
  93934. this._cameraRotationSpeed = 0;
  93935. this._lastFrameRadius = 0;
  93936. }
  93937. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93938. get: function () {
  93939. return "AutoRotation";
  93940. },
  93941. enumerable: true,
  93942. configurable: true
  93943. });
  93944. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93945. /**
  93946. * Gets the flag that indicates if user zooming should stop animation.
  93947. */
  93948. get: function () {
  93949. return this._zoomStopsAnimation;
  93950. },
  93951. /**
  93952. * Sets the flag that indicates if user zooming should stop animation.
  93953. */
  93954. set: function (flag) {
  93955. this._zoomStopsAnimation = flag;
  93956. },
  93957. enumerable: true,
  93958. configurable: true
  93959. });
  93960. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93961. /**
  93962. * Gets the default speed at which the camera rotates around the model.
  93963. */
  93964. get: function () {
  93965. return this._idleRotationSpeed;
  93966. },
  93967. /**
  93968. * Sets the default speed at which the camera rotates around the model.
  93969. */
  93970. set: function (speed) {
  93971. this._idleRotationSpeed = speed;
  93972. },
  93973. enumerable: true,
  93974. configurable: true
  93975. });
  93976. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93977. /**
  93978. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93979. */
  93980. get: function () {
  93981. return this._idleRotationWaitTime;
  93982. },
  93983. /**
  93984. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93985. */
  93986. set: function (time) {
  93987. this._idleRotationWaitTime = time;
  93988. },
  93989. enumerable: true,
  93990. configurable: true
  93991. });
  93992. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93993. /**
  93994. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93995. */
  93996. get: function () {
  93997. return this._idleRotationSpinupTime;
  93998. },
  93999. /**
  94000. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94001. */
  94002. set: function (time) {
  94003. this._idleRotationSpinupTime = time;
  94004. },
  94005. enumerable: true,
  94006. configurable: true
  94007. });
  94008. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94009. /**
  94010. * Gets a value indicating if the camera is currently rotating because of this behavior
  94011. */
  94012. get: function () {
  94013. return Math.abs(this._cameraRotationSpeed) > 0;
  94014. },
  94015. enumerable: true,
  94016. configurable: true
  94017. });
  94018. AutoRotationBehavior.prototype.init = function () {
  94019. // Do notihng
  94020. };
  94021. AutoRotationBehavior.prototype.attach = function (camera) {
  94022. var _this = this;
  94023. this._attachedCamera = camera;
  94024. var scene = this._attachedCamera.getScene();
  94025. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94026. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94027. _this._isPointerDown = true;
  94028. return;
  94029. }
  94030. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94031. _this._isPointerDown = false;
  94032. }
  94033. });
  94034. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94035. var now = BABYLON.Tools.Now;
  94036. var dt = 0;
  94037. if (_this._lastFrameTime != null) {
  94038. dt = now - _this._lastFrameTime;
  94039. }
  94040. _this._lastFrameTime = now;
  94041. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94042. _this._applyUserInteraction();
  94043. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94044. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94045. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94046. // Step camera rotation by rotation speed
  94047. if (_this._attachedCamera) {
  94048. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94049. }
  94050. });
  94051. };
  94052. AutoRotationBehavior.prototype.detach = function () {
  94053. if (!this._attachedCamera) {
  94054. return;
  94055. }
  94056. var scene = this._attachedCamera.getScene();
  94057. if (this._onPrePointerObservableObserver) {
  94058. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94059. }
  94060. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94061. this._attachedCamera = null;
  94062. };
  94063. /**
  94064. * Returns true if user is scrolling.
  94065. * @return true if user is scrolling.
  94066. */
  94067. AutoRotationBehavior.prototype._userIsZooming = function () {
  94068. if (!this._attachedCamera) {
  94069. return false;
  94070. }
  94071. return this._attachedCamera.inertialRadiusOffset !== 0;
  94072. };
  94073. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94074. if (!this._attachedCamera) {
  94075. return false;
  94076. }
  94077. var zoomHasHitLimit = false;
  94078. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94079. zoomHasHitLimit = true;
  94080. }
  94081. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94082. this._lastFrameRadius = this._attachedCamera.radius;
  94083. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94084. };
  94085. /**
  94086. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94087. */
  94088. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94089. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94090. this._lastInteractionTime = BABYLON.Tools.Now;
  94091. }
  94092. };
  94093. // Tools
  94094. AutoRotationBehavior.prototype._userIsMoving = function () {
  94095. if (!this._attachedCamera) {
  94096. return false;
  94097. }
  94098. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94099. this._attachedCamera.inertialBetaOffset !== 0 ||
  94100. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94101. this._attachedCamera.inertialPanningX !== 0 ||
  94102. this._attachedCamera.inertialPanningY !== 0 ||
  94103. this._isPointerDown;
  94104. };
  94105. return AutoRotationBehavior;
  94106. }());
  94107. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94108. })(BABYLON || (BABYLON = {}));
  94109. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94110. var BABYLON;
  94111. (function (BABYLON) {
  94112. var NullEngineOptions = /** @class */ (function () {
  94113. function NullEngineOptions() {
  94114. this.renderWidth = 512;
  94115. this.renderHeight = 256;
  94116. this.textureSize = 512;
  94117. this.deterministicLockstep = false;
  94118. this.lockstepMaxSteps = 4;
  94119. }
  94120. return NullEngineOptions;
  94121. }());
  94122. BABYLON.NullEngineOptions = NullEngineOptions;
  94123. /**
  94124. * The null engine class provides support for headless version of babylon.js.
  94125. * This can be used in server side scenario or for testing purposes
  94126. */
  94127. var NullEngine = /** @class */ (function (_super) {
  94128. __extends(NullEngine, _super);
  94129. function NullEngine(options) {
  94130. if (options === void 0) { options = new NullEngineOptions(); }
  94131. var _this = _super.call(this, null) || this;
  94132. if (options.deterministicLockstep === undefined) {
  94133. options.deterministicLockstep = false;
  94134. }
  94135. if (options.lockstepMaxSteps === undefined) {
  94136. options.lockstepMaxSteps = 4;
  94137. }
  94138. _this._options = options;
  94139. // Init caps
  94140. // We consider we are on a webgl1 capable device
  94141. _this._caps = new BABYLON.EngineCapabilities();
  94142. _this._caps.maxTexturesImageUnits = 16;
  94143. _this._caps.maxVertexTextureImageUnits = 16;
  94144. _this._caps.maxTextureSize = 512;
  94145. _this._caps.maxCubemapTextureSize = 512;
  94146. _this._caps.maxRenderTextureSize = 512;
  94147. _this._caps.maxVertexAttribs = 16;
  94148. _this._caps.maxVaryingVectors = 16;
  94149. _this._caps.maxFragmentUniformVectors = 16;
  94150. _this._caps.maxVertexUniformVectors = 16;
  94151. // Extensions
  94152. _this._caps.standardDerivatives = false;
  94153. _this._caps.astc = null;
  94154. _this._caps.s3tc = null;
  94155. _this._caps.pvrtc = null;
  94156. _this._caps.etc1 = null;
  94157. _this._caps.etc2 = null;
  94158. _this._caps.textureAnisotropicFilterExtension = null;
  94159. _this._caps.maxAnisotropy = 0;
  94160. _this._caps.uintIndices = false;
  94161. _this._caps.fragmentDepthSupported = false;
  94162. _this._caps.highPrecisionShaderSupported = true;
  94163. _this._caps.colorBufferFloat = false;
  94164. _this._caps.textureFloat = false;
  94165. _this._caps.textureFloatLinearFiltering = false;
  94166. _this._caps.textureFloatRender = false;
  94167. _this._caps.textureHalfFloat = false;
  94168. _this._caps.textureHalfFloatLinearFiltering = false;
  94169. _this._caps.textureHalfFloatRender = false;
  94170. _this._caps.textureLOD = false;
  94171. _this._caps.drawBuffersExtension = false;
  94172. _this._caps.depthTextureExtension = false;
  94173. _this._caps.vertexArrayObject = false;
  94174. _this._caps.instancedArrays = false;
  94175. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94176. // Wrappers
  94177. if (typeof URL === "undefined") {
  94178. URL = {
  94179. createObjectURL: function () { },
  94180. revokeObjectURL: function () { }
  94181. };
  94182. }
  94183. if (typeof Blob === "undefined") {
  94184. Blob = function () { };
  94185. }
  94186. return _this;
  94187. }
  94188. NullEngine.prototype.isDeterministicLockStep = function () {
  94189. return this._options.deterministicLockstep;
  94190. };
  94191. NullEngine.prototype.getLockstepMaxSteps = function () {
  94192. return this._options.lockstepMaxSteps;
  94193. };
  94194. NullEngine.prototype.getHardwareScalingLevel = function () {
  94195. return 1.0;
  94196. };
  94197. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94198. return {
  94199. capacity: 0,
  94200. references: 1,
  94201. is32Bits: false
  94202. };
  94203. };
  94204. NullEngine.prototype.createIndexBuffer = function (indices) {
  94205. return {
  94206. capacity: 0,
  94207. references: 1,
  94208. is32Bits: false
  94209. };
  94210. };
  94211. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94212. if (stencil === void 0) { stencil = false; }
  94213. };
  94214. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94215. if (useScreen === void 0) { useScreen = false; }
  94216. if (!useScreen && this._currentRenderTarget) {
  94217. return this._currentRenderTarget.width;
  94218. }
  94219. return this._options.renderWidth;
  94220. };
  94221. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94222. if (useScreen === void 0) { useScreen = false; }
  94223. if (!useScreen && this._currentRenderTarget) {
  94224. return this._currentRenderTarget.height;
  94225. }
  94226. return this._options.renderHeight;
  94227. };
  94228. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94229. this._cachedViewport = viewport;
  94230. };
  94231. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94232. return {
  94233. transformFeedback: null,
  94234. __SPECTOR_rebuildProgram: null
  94235. };
  94236. };
  94237. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94238. return [];
  94239. };
  94240. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94241. return [];
  94242. };
  94243. NullEngine.prototype.bindSamplers = function (effect) {
  94244. this._currentEffect = null;
  94245. };
  94246. NullEngine.prototype.enableEffect = function (effect) {
  94247. this._currentEffect = effect;
  94248. if (effect.onBind) {
  94249. effect.onBind(effect);
  94250. }
  94251. effect.onBindObservable.notifyObservers(effect);
  94252. };
  94253. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94254. if (zOffset === void 0) { zOffset = 0; }
  94255. if (reverseSide === void 0) { reverseSide = false; }
  94256. };
  94257. NullEngine.prototype.setIntArray = function (uniform, array) {
  94258. };
  94259. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94260. };
  94261. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94262. };
  94263. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94264. };
  94265. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94266. };
  94267. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94268. };
  94269. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94270. };
  94271. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94272. };
  94273. NullEngine.prototype.setArray = function (uniform, array) {
  94274. };
  94275. NullEngine.prototype.setArray2 = function (uniform, array) {
  94276. };
  94277. NullEngine.prototype.setArray3 = function (uniform, array) {
  94278. };
  94279. NullEngine.prototype.setArray4 = function (uniform, array) {
  94280. };
  94281. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94282. };
  94283. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94284. };
  94285. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94286. };
  94287. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94288. };
  94289. NullEngine.prototype.setFloat = function (uniform, value) {
  94290. };
  94291. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94292. };
  94293. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94294. };
  94295. NullEngine.prototype.setBool = function (uniform, bool) {
  94296. };
  94297. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94298. };
  94299. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94300. };
  94301. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94302. };
  94303. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94304. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94305. if (this._alphaMode === mode) {
  94306. return;
  94307. }
  94308. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94309. if (!noDepthWriteChange) {
  94310. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94311. }
  94312. this._alphaMode = mode;
  94313. };
  94314. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94315. };
  94316. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94317. if (this.preventCacheWipeBetweenFrames) {
  94318. return;
  94319. }
  94320. this.resetTextureCache();
  94321. this._currentEffect = null;
  94322. if (bruteForce) {
  94323. this._currentProgram = null;
  94324. this._stencilState.reset();
  94325. this._depthCullingState.reset();
  94326. this._alphaState.reset();
  94327. }
  94328. this._cachedVertexBuffers = null;
  94329. this._cachedIndexBuffer = null;
  94330. this._cachedEffectForVertexBuffers = null;
  94331. };
  94332. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94333. };
  94334. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94335. };
  94336. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94337. };
  94338. NullEngine.prototype._createTexture = function () {
  94339. return {};
  94340. };
  94341. NullEngine.prototype._releaseTexture = function (texture) {
  94342. };
  94343. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94345. if (onLoad === void 0) { onLoad = null; }
  94346. if (onError === void 0) { onError = null; }
  94347. if (buffer === void 0) { buffer = null; }
  94348. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94349. var url = String(urlArg);
  94350. texture.url = url;
  94351. texture.generateMipMaps = !noMipmap;
  94352. texture.samplingMode = samplingMode;
  94353. texture.invertY = invertY;
  94354. texture.baseWidth = this._options.textureSize;
  94355. texture.baseHeight = this._options.textureSize;
  94356. texture.width = this._options.textureSize;
  94357. texture.height = this._options.textureSize;
  94358. if (format) {
  94359. texture.format = format;
  94360. }
  94361. texture.isReady = true;
  94362. if (onLoad) {
  94363. onLoad();
  94364. }
  94365. return texture;
  94366. };
  94367. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94368. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94369. if (options !== undefined && typeof options === "object") {
  94370. fullOptions.generateMipMaps = options.generateMipMaps;
  94371. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94372. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94373. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  94374. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  94375. }
  94376. else {
  94377. fullOptions.generateMipMaps = options;
  94378. fullOptions.generateDepthBuffer = true;
  94379. fullOptions.generateStencilBuffer = false;
  94380. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94381. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  94382. }
  94383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  94384. var width = size.width || size;
  94385. var height = size.height || size;
  94386. texture._depthStencilBuffer = {};
  94387. texture._framebuffer = {};
  94388. texture.baseWidth = width;
  94389. texture.baseHeight = height;
  94390. texture.width = width;
  94391. texture.height = height;
  94392. texture.isReady = true;
  94393. texture.samples = 1;
  94394. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  94395. texture.samplingMode = fullOptions.samplingMode;
  94396. texture.type = fullOptions.type;
  94397. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  94398. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  94399. return texture;
  94400. };
  94401. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  94402. texture.samplingMode = samplingMode;
  94403. };
  94404. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  94405. if (this._currentRenderTarget) {
  94406. this.unBindFramebuffer(this._currentRenderTarget);
  94407. }
  94408. this._currentRenderTarget = texture;
  94409. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  94410. if (this._cachedViewport && !forceFullscreenViewport) {
  94411. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  94412. }
  94413. };
  94414. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  94415. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  94416. this._currentRenderTarget = null;
  94417. if (onBeforeUnbind) {
  94418. if (texture._MSAAFramebuffer) {
  94419. this._currentFramebuffer = texture._framebuffer;
  94420. }
  94421. onBeforeUnbind();
  94422. }
  94423. this._currentFramebuffer = null;
  94424. };
  94425. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  94426. var vbo = {
  94427. capacity: 1,
  94428. references: 1,
  94429. is32Bits: false
  94430. };
  94431. return vbo;
  94432. };
  94433. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  94434. if (offset === void 0) { offset = 0; }
  94435. };
  94436. /**
  94437. * Updates a dynamic vertex buffer.
  94438. * @param vertexBuffer the vertex buffer to update
  94439. * @param data the data used to update the vertex buffer
  94440. * @param byteOffset the byte offset of the data (optional)
  94441. * @param byteLength the byte length of the data (optional)
  94442. */
  94443. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  94444. };
  94445. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  94446. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  94447. this._boundTexturesCache[this._activeChannel] = texture;
  94448. }
  94449. };
  94450. NullEngine.prototype._bindTexture = function (channel, texture) {
  94451. if (channel < 0) {
  94452. return;
  94453. }
  94454. this._bindTextureDirectly(0, texture);
  94455. };
  94456. NullEngine.prototype._releaseBuffer = function (buffer) {
  94457. buffer.references--;
  94458. if (buffer.references === 0) {
  94459. return true;
  94460. }
  94461. return false;
  94462. };
  94463. return NullEngine;
  94464. }(BABYLON.Engine));
  94465. BABYLON.NullEngine = NullEngine;
  94466. })(BABYLON || (BABYLON = {}));
  94467. //# sourceMappingURL=babylon.nullEngine.js.map
  94468. var BABYLON;
  94469. (function (BABYLON) {
  94470. /**
  94471. * This class can be used to get instrumentation data from a Babylon engine
  94472. */
  94473. var EngineInstrumentation = /** @class */ (function () {
  94474. function EngineInstrumentation(engine) {
  94475. this.engine = engine;
  94476. this._captureGPUFrameTime = false;
  94477. this._gpuFrameTime = new BABYLON.PerfCounter();
  94478. this._captureShaderCompilationTime = false;
  94479. this._shaderCompilationTime = new BABYLON.PerfCounter();
  94480. // Observers
  94481. this._onBeginFrameObserver = null;
  94482. this._onEndFrameObserver = null;
  94483. this._onBeforeShaderCompilationObserver = null;
  94484. this._onAfterShaderCompilationObserver = null;
  94485. }
  94486. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  94487. // Properties
  94488. /**
  94489. * Gets the perf counter used for GPU frame time
  94490. */
  94491. get: function () {
  94492. return this._gpuFrameTime;
  94493. },
  94494. enumerable: true,
  94495. configurable: true
  94496. });
  94497. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  94498. /**
  94499. * Gets the GPU frame time capture status
  94500. */
  94501. get: function () {
  94502. return this._captureGPUFrameTime;
  94503. },
  94504. /**
  94505. * Enable or disable the GPU frame time capture
  94506. */
  94507. set: function (value) {
  94508. var _this = this;
  94509. if (value === this._captureGPUFrameTime) {
  94510. return;
  94511. }
  94512. this._captureGPUFrameTime = value;
  94513. if (value) {
  94514. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  94515. if (!_this._gpuFrameTimeToken) {
  94516. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  94517. }
  94518. });
  94519. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  94520. if (!_this._gpuFrameTimeToken) {
  94521. return;
  94522. }
  94523. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  94524. if (time > -1) {
  94525. _this._gpuFrameTimeToken = null;
  94526. _this._gpuFrameTime.fetchNewFrame();
  94527. _this._gpuFrameTime.addCount(time, true);
  94528. }
  94529. });
  94530. }
  94531. else {
  94532. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94533. this._onBeginFrameObserver = null;
  94534. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94535. this._onEndFrameObserver = null;
  94536. }
  94537. },
  94538. enumerable: true,
  94539. configurable: true
  94540. });
  94541. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  94542. /**
  94543. * Gets the perf counter used for shader compilation time
  94544. */
  94545. get: function () {
  94546. return this._shaderCompilationTime;
  94547. },
  94548. enumerable: true,
  94549. configurable: true
  94550. });
  94551. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  94552. /**
  94553. * Gets the shader compilation time capture status
  94554. */
  94555. get: function () {
  94556. return this._captureShaderCompilationTime;
  94557. },
  94558. /**
  94559. * Enable or disable the shader compilation time capture
  94560. */
  94561. set: function (value) {
  94562. var _this = this;
  94563. if (value === this._captureShaderCompilationTime) {
  94564. return;
  94565. }
  94566. this._captureShaderCompilationTime = value;
  94567. if (value) {
  94568. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  94569. _this._shaderCompilationTime.fetchNewFrame();
  94570. _this._shaderCompilationTime.beginMonitoring();
  94571. });
  94572. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  94573. _this._shaderCompilationTime.endMonitoring();
  94574. });
  94575. }
  94576. else {
  94577. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94578. this._onBeforeShaderCompilationObserver = null;
  94579. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94580. this._onAfterShaderCompilationObserver = null;
  94581. }
  94582. },
  94583. enumerable: true,
  94584. configurable: true
  94585. });
  94586. EngineInstrumentation.prototype.dispose = function () {
  94587. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94588. this._onBeginFrameObserver = null;
  94589. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94590. this._onEndFrameObserver = null;
  94591. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94592. this._onBeforeShaderCompilationObserver = null;
  94593. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94594. this._onAfterShaderCompilationObserver = null;
  94595. this.engine = null;
  94596. };
  94597. return EngineInstrumentation;
  94598. }());
  94599. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94600. })(BABYLON || (BABYLON = {}));
  94601. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94602. var BABYLON;
  94603. (function (BABYLON) {
  94604. /**
  94605. * This class can be used to get instrumentation data from a Babylon engine
  94606. */
  94607. var SceneInstrumentation = /** @class */ (function () {
  94608. function SceneInstrumentation(scene) {
  94609. var _this = this;
  94610. this.scene = scene;
  94611. this._captureActiveMeshesEvaluationTime = false;
  94612. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94613. this._captureRenderTargetsRenderTime = false;
  94614. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94615. this._captureFrameTime = false;
  94616. this._frameTime = new BABYLON.PerfCounter();
  94617. this._captureRenderTime = false;
  94618. this._renderTime = new BABYLON.PerfCounter();
  94619. this._captureInterFrameTime = false;
  94620. this._interFrameTime = new BABYLON.PerfCounter();
  94621. this._captureParticlesRenderTime = false;
  94622. this._particlesRenderTime = new BABYLON.PerfCounter();
  94623. this._captureSpritesRenderTime = false;
  94624. this._spritesRenderTime = new BABYLON.PerfCounter();
  94625. this._capturePhysicsTime = false;
  94626. this._physicsTime = new BABYLON.PerfCounter();
  94627. this._captureAnimationsTime = false;
  94628. this._animationsTime = new BABYLON.PerfCounter();
  94629. // Observers
  94630. this._onBeforeActiveMeshesEvaluationObserver = null;
  94631. this._onAfterActiveMeshesEvaluationObserver = null;
  94632. this._onBeforeRenderTargetsRenderObserver = null;
  94633. this._onAfterRenderTargetsRenderObserver = null;
  94634. this._onAfterRenderObserver = null;
  94635. this._onBeforeDrawPhaseObserver = null;
  94636. this._onAfterDrawPhaseObserver = null;
  94637. this._onBeforeAnimationsObserver = null;
  94638. this._onBeforeParticlesRenderingObserver = null;
  94639. this._onAfterParticlesRenderingObserver = null;
  94640. this._onBeforeSpritesRenderingObserver = null;
  94641. this._onAfterSpritesRenderingObserver = null;
  94642. this._onBeforePhysicsObserver = null;
  94643. this._onAfterPhysicsObserver = null;
  94644. this._onAfterAnimationsObserver = null;
  94645. // Before render
  94646. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94647. if (_this._captureActiveMeshesEvaluationTime) {
  94648. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94649. }
  94650. if (_this._captureRenderTargetsRenderTime) {
  94651. _this._renderTargetsRenderTime.fetchNewFrame();
  94652. }
  94653. if (_this._captureFrameTime) {
  94654. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94655. _this._frameTime.beginMonitoring();
  94656. }
  94657. if (_this._captureInterFrameTime) {
  94658. _this._interFrameTime.endMonitoring();
  94659. }
  94660. if (_this._captureParticlesRenderTime) {
  94661. _this._particlesRenderTime.fetchNewFrame();
  94662. }
  94663. if (_this._captureSpritesRenderTime) {
  94664. _this._spritesRenderTime.fetchNewFrame();
  94665. }
  94666. if (_this._captureAnimationsTime) {
  94667. _this._animationsTime.beginMonitoring();
  94668. }
  94669. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94670. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94671. });
  94672. // After render
  94673. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94674. if (_this._captureFrameTime) {
  94675. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94676. _this._frameTime.endMonitoring();
  94677. }
  94678. if (_this._captureRenderTime) {
  94679. _this._renderTime.endMonitoring(false);
  94680. }
  94681. if (_this._captureInterFrameTime) {
  94682. _this._interFrameTime.beginMonitoring();
  94683. }
  94684. });
  94685. }
  94686. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94687. // Properties
  94688. /**
  94689. * Gets the perf counter used for active meshes evaluation time
  94690. */
  94691. get: function () {
  94692. return this._activeMeshesEvaluationTime;
  94693. },
  94694. enumerable: true,
  94695. configurable: true
  94696. });
  94697. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94698. /**
  94699. * Gets the active meshes evaluation time capture status
  94700. */
  94701. get: function () {
  94702. return this._captureActiveMeshesEvaluationTime;
  94703. },
  94704. /**
  94705. * Enable or disable the active meshes evaluation time capture
  94706. */
  94707. set: function (value) {
  94708. var _this = this;
  94709. if (value === this._captureActiveMeshesEvaluationTime) {
  94710. return;
  94711. }
  94712. this._captureActiveMeshesEvaluationTime = value;
  94713. if (value) {
  94714. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94715. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94716. _this._activeMeshesEvaluationTime.beginMonitoring();
  94717. });
  94718. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94719. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94720. _this._activeMeshesEvaluationTime.endMonitoring();
  94721. });
  94722. }
  94723. else {
  94724. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94725. this._onBeforeActiveMeshesEvaluationObserver = null;
  94726. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94727. this._onAfterActiveMeshesEvaluationObserver = null;
  94728. }
  94729. },
  94730. enumerable: true,
  94731. configurable: true
  94732. });
  94733. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94734. /**
  94735. * Gets the perf counter used for render targets render time
  94736. */
  94737. get: function () {
  94738. return this._renderTargetsRenderTime;
  94739. },
  94740. enumerable: true,
  94741. configurable: true
  94742. });
  94743. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94744. /**
  94745. * Gets the render targets render time capture status
  94746. */
  94747. get: function () {
  94748. return this._captureRenderTargetsRenderTime;
  94749. },
  94750. /**
  94751. * Enable or disable the render targets render time capture
  94752. */
  94753. set: function (value) {
  94754. var _this = this;
  94755. if (value === this._captureRenderTargetsRenderTime) {
  94756. return;
  94757. }
  94758. this._captureRenderTargetsRenderTime = value;
  94759. if (value) {
  94760. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94761. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94762. _this._renderTargetsRenderTime.beginMonitoring();
  94763. });
  94764. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94765. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94766. _this._renderTargetsRenderTime.endMonitoring(false);
  94767. });
  94768. }
  94769. else {
  94770. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94771. this._onBeforeRenderTargetsRenderObserver = null;
  94772. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94773. this._onAfterRenderTargetsRenderObserver = null;
  94774. }
  94775. },
  94776. enumerable: true,
  94777. configurable: true
  94778. });
  94779. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94780. /**
  94781. * Gets the perf counter used for particles render time
  94782. */
  94783. get: function () {
  94784. return this._particlesRenderTime;
  94785. },
  94786. enumerable: true,
  94787. configurable: true
  94788. });
  94789. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94790. /**
  94791. * Gets the particles render time capture status
  94792. */
  94793. get: function () {
  94794. return this._captureParticlesRenderTime;
  94795. },
  94796. /**
  94797. * Enable or disable the particles render time capture
  94798. */
  94799. set: function (value) {
  94800. var _this = this;
  94801. if (value === this._captureParticlesRenderTime) {
  94802. return;
  94803. }
  94804. this._captureParticlesRenderTime = value;
  94805. if (value) {
  94806. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94807. BABYLON.Tools.StartPerformanceCounter("Particles");
  94808. _this._particlesRenderTime.beginMonitoring();
  94809. });
  94810. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94811. BABYLON.Tools.EndPerformanceCounter("Particles");
  94812. _this._particlesRenderTime.endMonitoring(false);
  94813. });
  94814. }
  94815. else {
  94816. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94817. this._onBeforeParticlesRenderingObserver = null;
  94818. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94819. this._onAfterParticlesRenderingObserver = null;
  94820. }
  94821. },
  94822. enumerable: true,
  94823. configurable: true
  94824. });
  94825. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94826. /**
  94827. * Gets the perf counter used for sprites render time
  94828. */
  94829. get: function () {
  94830. return this._spritesRenderTime;
  94831. },
  94832. enumerable: true,
  94833. configurable: true
  94834. });
  94835. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94836. /**
  94837. * Gets the sprites render time capture status
  94838. */
  94839. get: function () {
  94840. return this._captureSpritesRenderTime;
  94841. },
  94842. /**
  94843. * Enable or disable the sprites render time capture
  94844. */
  94845. set: function (value) {
  94846. var _this = this;
  94847. if (value === this._captureSpritesRenderTime) {
  94848. return;
  94849. }
  94850. this._captureSpritesRenderTime = value;
  94851. if (value) {
  94852. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94853. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94854. _this._spritesRenderTime.beginMonitoring();
  94855. });
  94856. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94857. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94858. _this._spritesRenderTime.endMonitoring(false);
  94859. });
  94860. }
  94861. else {
  94862. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94863. this._onBeforeSpritesRenderingObserver = null;
  94864. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94865. this._onAfterSpritesRenderingObserver = null;
  94866. }
  94867. },
  94868. enumerable: true,
  94869. configurable: true
  94870. });
  94871. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94872. /**
  94873. * Gets the perf counter used for physics time
  94874. */
  94875. get: function () {
  94876. return this._physicsTime;
  94877. },
  94878. enumerable: true,
  94879. configurable: true
  94880. });
  94881. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94882. /**
  94883. * Gets the physics time capture status
  94884. */
  94885. get: function () {
  94886. return this._capturePhysicsTime;
  94887. },
  94888. /**
  94889. * Enable or disable the physics time capture
  94890. */
  94891. set: function (value) {
  94892. var _this = this;
  94893. if (value === this._capturePhysicsTime) {
  94894. return;
  94895. }
  94896. this._capturePhysicsTime = value;
  94897. if (value) {
  94898. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94899. BABYLON.Tools.StartPerformanceCounter("Physics");
  94900. _this._physicsTime.beginMonitoring();
  94901. });
  94902. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94903. BABYLON.Tools.EndPerformanceCounter("Physics");
  94904. _this._physicsTime.endMonitoring();
  94905. });
  94906. }
  94907. else {
  94908. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94909. this._onBeforePhysicsObserver = null;
  94910. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94911. this._onAfterPhysicsObserver = null;
  94912. }
  94913. },
  94914. enumerable: true,
  94915. configurable: true
  94916. });
  94917. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94918. /**
  94919. * Gets the perf counter used for animations time
  94920. */
  94921. get: function () {
  94922. return this._animationsTime;
  94923. },
  94924. enumerable: true,
  94925. configurable: true
  94926. });
  94927. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94928. /**
  94929. * Gets the animations time capture status
  94930. */
  94931. get: function () {
  94932. return this._captureAnimationsTime;
  94933. },
  94934. /**
  94935. * Enable or disable the animations time capture
  94936. */
  94937. set: function (value) {
  94938. var _this = this;
  94939. if (value === this._captureAnimationsTime) {
  94940. return;
  94941. }
  94942. this._captureAnimationsTime = value;
  94943. if (value) {
  94944. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94945. _this._animationsTime.endMonitoring();
  94946. });
  94947. }
  94948. else {
  94949. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94950. this._onAfterAnimationsObserver = null;
  94951. }
  94952. },
  94953. enumerable: true,
  94954. configurable: true
  94955. });
  94956. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94957. /**
  94958. * Gets the perf counter used for frame time capture
  94959. */
  94960. get: function () {
  94961. return this._frameTime;
  94962. },
  94963. enumerable: true,
  94964. configurable: true
  94965. });
  94966. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94967. /**
  94968. * Gets the frame time capture status
  94969. */
  94970. get: function () {
  94971. return this._captureFrameTime;
  94972. },
  94973. /**
  94974. * Enable or disable the frame time capture
  94975. */
  94976. set: function (value) {
  94977. this._captureFrameTime = value;
  94978. },
  94979. enumerable: true,
  94980. configurable: true
  94981. });
  94982. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94983. /**
  94984. * Gets the perf counter used for inter-frames time capture
  94985. */
  94986. get: function () {
  94987. return this._interFrameTime;
  94988. },
  94989. enumerable: true,
  94990. configurable: true
  94991. });
  94992. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94993. /**
  94994. * Gets the inter-frames time capture status
  94995. */
  94996. get: function () {
  94997. return this._captureInterFrameTime;
  94998. },
  94999. /**
  95000. * Enable or disable the inter-frames time capture
  95001. */
  95002. set: function (value) {
  95003. this._captureInterFrameTime = value;
  95004. },
  95005. enumerable: true,
  95006. configurable: true
  95007. });
  95008. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95009. /**
  95010. * Gets the perf counter used for render time capture
  95011. */
  95012. get: function () {
  95013. return this._renderTime;
  95014. },
  95015. enumerable: true,
  95016. configurable: true
  95017. });
  95018. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95019. /**
  95020. * Gets the render time capture status
  95021. */
  95022. get: function () {
  95023. return this._captureRenderTime;
  95024. },
  95025. /**
  95026. * Enable or disable the render time capture
  95027. */
  95028. set: function (value) {
  95029. var _this = this;
  95030. if (value === this._captureRenderTime) {
  95031. return;
  95032. }
  95033. this._captureRenderTime = value;
  95034. if (value) {
  95035. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95036. _this._renderTime.beginMonitoring();
  95037. BABYLON.Tools.StartPerformanceCounter("Main render");
  95038. });
  95039. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95040. _this._renderTime.endMonitoring(false);
  95041. BABYLON.Tools.EndPerformanceCounter("Main render");
  95042. });
  95043. }
  95044. else {
  95045. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95046. this._onBeforeDrawPhaseObserver = null;
  95047. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95048. this._onAfterDrawPhaseObserver = null;
  95049. }
  95050. },
  95051. enumerable: true,
  95052. configurable: true
  95053. });
  95054. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95055. /**
  95056. * Gets the perf counter used for draw calls
  95057. */
  95058. get: function () {
  95059. return this.scene.getEngine()._drawCalls;
  95060. },
  95061. enumerable: true,
  95062. configurable: true
  95063. });
  95064. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95065. /**
  95066. * Gets the perf counter used for texture collisions
  95067. */
  95068. get: function () {
  95069. return this.scene.getEngine()._textureCollisions;
  95070. },
  95071. enumerable: true,
  95072. configurable: true
  95073. });
  95074. SceneInstrumentation.prototype.dispose = function () {
  95075. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95076. this._onAfterRenderObserver = null;
  95077. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95078. this._onBeforeActiveMeshesEvaluationObserver = null;
  95079. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95080. this._onAfterActiveMeshesEvaluationObserver = null;
  95081. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95082. this._onBeforeRenderTargetsRenderObserver = null;
  95083. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95084. this._onAfterRenderTargetsRenderObserver = null;
  95085. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95086. this._onBeforeAnimationsObserver = null;
  95087. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95088. this._onBeforeParticlesRenderingObserver = null;
  95089. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95090. this._onAfterParticlesRenderingObserver = null;
  95091. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95092. this._onBeforeSpritesRenderingObserver = null;
  95093. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95094. this._onAfterSpritesRenderingObserver = null;
  95095. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95096. this._onBeforeDrawPhaseObserver = null;
  95097. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95098. this._onAfterDrawPhaseObserver = null;
  95099. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95100. this._onBeforePhysicsObserver = null;
  95101. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95102. this._onAfterPhysicsObserver = null;
  95103. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95104. this._onAfterAnimationsObserver = null;
  95105. this.scene = null;
  95106. };
  95107. return SceneInstrumentation;
  95108. }());
  95109. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95110. })(BABYLON || (BABYLON = {}));
  95111. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95112. var BABYLON;
  95113. (function (BABYLON) {
  95114. var _TimeToken = /** @class */ (function () {
  95115. function _TimeToken() {
  95116. this._timeElapsedQueryEnded = false;
  95117. }
  95118. return _TimeToken;
  95119. }());
  95120. BABYLON._TimeToken = _TimeToken;
  95121. })(BABYLON || (BABYLON = {}));
  95122. //# sourceMappingURL=babylon.timeToken.js.map
  95123. var BABYLON;
  95124. (function (BABYLON) {
  95125. /**
  95126. * Background material defines definition.
  95127. * @ignore Mainly internal Use
  95128. */
  95129. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95130. __extends(BackgroundMaterialDefines, _super);
  95131. /**
  95132. * Constructor of the defines.
  95133. */
  95134. function BackgroundMaterialDefines() {
  95135. var _this = _super.call(this) || this;
  95136. /**
  95137. * True if the diffuse texture is in use.
  95138. */
  95139. _this.DIFFUSE = false;
  95140. /**
  95141. * The direct UV channel to use.
  95142. */
  95143. _this.DIFFUSEDIRECTUV = 0;
  95144. /**
  95145. * True if the diffuse texture is in gamma space.
  95146. */
  95147. _this.GAMMADIFFUSE = false;
  95148. /**
  95149. * True if the diffuse texture has opacity in the alpha channel.
  95150. */
  95151. _this.DIFFUSEHASALPHA = false;
  95152. /**
  95153. * True if you want the material to fade to transparent at grazing angle.
  95154. */
  95155. _this.OPACITYFRESNEL = false;
  95156. /**
  95157. * True if an extra blur needs to be added in the reflection.
  95158. */
  95159. _this.REFLECTIONBLUR = false;
  95160. /**
  95161. * True if you want the material to fade to reflection at grazing angle.
  95162. */
  95163. _this.REFLECTIONFRESNEL = false;
  95164. /**
  95165. * True if you want the material to falloff as far as you move away from the scene center.
  95166. */
  95167. _this.REFLECTIONFALLOFF = false;
  95168. /**
  95169. * False if the current Webgl implementation does not support the texture lod extension.
  95170. */
  95171. _this.TEXTURELODSUPPORT = false;
  95172. /**
  95173. * True to ensure the data are premultiplied.
  95174. */
  95175. _this.PREMULTIPLYALPHA = false;
  95176. /**
  95177. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95178. */
  95179. _this.USERGBCOLOR = false;
  95180. /**
  95181. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95182. * stays aligned with the desired configuration.
  95183. */
  95184. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95185. /**
  95186. * True to add noise in order to reduce the banding effect.
  95187. */
  95188. _this.NOISE = false;
  95189. /**
  95190. * is the reflection texture in BGR color scheme?
  95191. * Mainly used to solve a bug in ios10 video tag
  95192. */
  95193. _this.REFLECTIONBGR = false;
  95194. _this.IMAGEPROCESSING = false;
  95195. _this.VIGNETTE = false;
  95196. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95197. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95198. _this.TONEMAPPING = false;
  95199. _this.CONTRAST = false;
  95200. _this.COLORCURVES = false;
  95201. _this.COLORGRADING = false;
  95202. _this.COLORGRADING3D = false;
  95203. _this.SAMPLER3DGREENDEPTH = false;
  95204. _this.SAMPLER3DBGRMAP = false;
  95205. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95206. _this.EXPOSURE = false;
  95207. // Reflection.
  95208. _this.REFLECTION = false;
  95209. _this.REFLECTIONMAP_3D = false;
  95210. _this.REFLECTIONMAP_SPHERICAL = false;
  95211. _this.REFLECTIONMAP_PLANAR = false;
  95212. _this.REFLECTIONMAP_CUBIC = false;
  95213. _this.REFLECTIONMAP_PROJECTION = false;
  95214. _this.REFLECTIONMAP_SKYBOX = false;
  95215. _this.REFLECTIONMAP_EXPLICIT = false;
  95216. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95217. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95218. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95219. _this.INVERTCUBICMAP = false;
  95220. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95221. _this.LODINREFLECTIONALPHA = false;
  95222. _this.GAMMAREFLECTION = false;
  95223. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95224. // Default BJS.
  95225. _this.MAINUV1 = false;
  95226. _this.MAINUV2 = false;
  95227. _this.UV1 = false;
  95228. _this.UV2 = false;
  95229. _this.CLIPPLANE = false;
  95230. _this.POINTSIZE = false;
  95231. _this.FOG = false;
  95232. _this.NORMAL = false;
  95233. _this.NUM_BONE_INFLUENCERS = 0;
  95234. _this.BonesPerMesh = 0;
  95235. _this.INSTANCES = false;
  95236. _this.SHADOWFLOAT = false;
  95237. _this.rebuild();
  95238. return _this;
  95239. }
  95240. return BackgroundMaterialDefines;
  95241. }(BABYLON.MaterialDefines));
  95242. /**
  95243. * Background material used to create an efficient environement around your scene.
  95244. */
  95245. var BackgroundMaterial = /** @class */ (function (_super) {
  95246. __extends(BackgroundMaterial, _super);
  95247. /**
  95248. * Instantiates a Background Material in the given scene
  95249. * @param name The friendly name of the material
  95250. * @param scene The scene to add the material to
  95251. */
  95252. function BackgroundMaterial(name, scene) {
  95253. var _this = _super.call(this, name, scene) || this;
  95254. /**
  95255. * Key light Color (multiply against the environement texture)
  95256. */
  95257. _this.primaryColor = BABYLON.Color3.White();
  95258. _this._primaryColorShadowLevel = 0;
  95259. _this._primaryColorHighlightLevel = 0;
  95260. /**
  95261. * Reflection Texture used in the material.
  95262. * Should be author in a specific way for the best result (refer to the documentation).
  95263. */
  95264. _this.reflectionTexture = null;
  95265. /**
  95266. * Reflection Texture level of blur.
  95267. *
  95268. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95269. * texture twice.
  95270. */
  95271. _this.reflectionBlur = 0;
  95272. /**
  95273. * Diffuse Texture used in the material.
  95274. * Should be author in a specific way for the best result (refer to the documentation).
  95275. */
  95276. _this.diffuseTexture = null;
  95277. _this._shadowLights = null;
  95278. /**
  95279. * Specify the list of lights casting shadow on the material.
  95280. * All scene shadow lights will be included if null.
  95281. */
  95282. _this.shadowLights = null;
  95283. /**
  95284. * Helps adjusting the shadow to a softer level if required.
  95285. * 0 means black shadows and 1 means no shadows.
  95286. */
  95287. _this.shadowLevel = 0;
  95288. /**
  95289. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95290. * It is usually zero but might be interesting to modify according to your setup.
  95291. */
  95292. _this.sceneCenter = BABYLON.Vector3.Zero();
  95293. /**
  95294. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95295. * This helps ensuring a nice transition when the camera goes under the ground.
  95296. */
  95297. _this.opacityFresnel = true;
  95298. /**
  95299. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95300. * This helps adding a mirror texture on the ground.
  95301. */
  95302. _this.reflectionFresnel = false;
  95303. /**
  95304. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95305. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95306. */
  95307. _this.reflectionFalloffDistance = 0.0;
  95308. /**
  95309. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95310. */
  95311. _this.reflectionAmount = 1.0;
  95312. /**
  95313. * This specifies the weight of the reflection at grazing angle.
  95314. */
  95315. _this.reflectionReflectance0 = 0.05;
  95316. /**
  95317. * This specifies the weight of the reflection at a perpendicular point of view.
  95318. */
  95319. _this.reflectionReflectance90 = 0.5;
  95320. /**
  95321. * Helps to directly use the maps channels instead of their level.
  95322. */
  95323. _this.useRGBColor = true;
  95324. /**
  95325. * This helps reducing the banding effect that could occur on the background.
  95326. */
  95327. _this.enableNoise = false;
  95328. _this._fovMultiplier = 1.0;
  95329. /**
  95330. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95331. */
  95332. _this.useEquirectangularFOV = false;
  95333. _this._maxSimultaneousLights = 4;
  95334. /**
  95335. * Number of Simultaneous lights allowed on the material.
  95336. */
  95337. _this.maxSimultaneousLights = 4;
  95338. /**
  95339. * Keep track of the image processing observer to allow dispose and replace.
  95340. */
  95341. _this._imageProcessingObserver = null;
  95342. /**
  95343. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95344. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95345. */
  95346. _this.switchToBGR = false;
  95347. // Temp values kept as cache in the material.
  95348. _this._renderTargets = new BABYLON.SmartArray(16);
  95349. _this._reflectionControls = BABYLON.Vector4.Zero();
  95350. _this._white = BABYLON.Color3.White();
  95351. _this._primaryShadowColor = BABYLON.Color3.Black();
  95352. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95353. // Setup the default processing configuration to the scene.
  95354. _this._attachImageProcessingConfiguration(null);
  95355. _this.getRenderTargetTextures = function () {
  95356. _this._renderTargets.reset();
  95357. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95358. _this._renderTargets.push(_this._diffuseTexture);
  95359. }
  95360. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95361. _this._renderTargets.push(_this._reflectionTexture);
  95362. }
  95363. return _this._renderTargets;
  95364. };
  95365. return _this;
  95366. }
  95367. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95368. /**
  95369. * Experimental Internal Use Only.
  95370. *
  95371. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  95372. * This acts as a helper to set the primary color to a more "human friendly" value.
  95373. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  95374. * output color as close as possible from the chosen value.
  95375. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  95376. * part of lighting setup.)
  95377. */
  95378. get: function () {
  95379. return this.__perceptualColor;
  95380. },
  95381. set: function (value) {
  95382. this.__perceptualColor = value;
  95383. this._computePrimaryColorFromPerceptualColor();
  95384. this._markAllSubMeshesAsLightsDirty();
  95385. },
  95386. enumerable: true,
  95387. configurable: true
  95388. });
  95389. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  95390. /**
  95391. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  95392. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  95393. */
  95394. get: function () {
  95395. return this._primaryColorShadowLevel;
  95396. },
  95397. set: function (value) {
  95398. this._primaryColorShadowLevel = value;
  95399. this._computePrimaryColors();
  95400. this._markAllSubMeshesAsLightsDirty();
  95401. },
  95402. enumerable: true,
  95403. configurable: true
  95404. });
  95405. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  95406. /**
  95407. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  95408. * The primary color is used at the level chosen to define what the white area would look.
  95409. */
  95410. get: function () {
  95411. return this._primaryColorHighlightLevel;
  95412. },
  95413. set: function (value) {
  95414. this._primaryColorHighlightLevel = value;
  95415. this._computePrimaryColors();
  95416. this._markAllSubMeshesAsLightsDirty();
  95417. },
  95418. enumerable: true,
  95419. configurable: true
  95420. });
  95421. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  95422. /**
  95423. * Sets the reflection reflectance fresnel values according to the default standard
  95424. * empirically know to work well :-)
  95425. */
  95426. set: function (value) {
  95427. var reflectionWeight = value;
  95428. if (reflectionWeight < 0.5) {
  95429. reflectionWeight = reflectionWeight * 2.0;
  95430. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  95431. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  95432. }
  95433. else {
  95434. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  95435. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  95436. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  95437. }
  95438. },
  95439. enumerable: true,
  95440. configurable: true
  95441. });
  95442. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  95443. /**
  95444. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95445. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  95446. * Recommended to be keep at 1.0 except for special cases.
  95447. */
  95448. get: function () {
  95449. return this._fovMultiplier;
  95450. },
  95451. set: function (value) {
  95452. if (isNaN(value)) {
  95453. value = 1.0;
  95454. }
  95455. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  95456. },
  95457. enumerable: true,
  95458. configurable: true
  95459. });
  95460. /**
  95461. * Attaches a new image processing configuration to the PBR Material.
  95462. * @param configuration (if null the scene configuration will be use)
  95463. */
  95464. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  95465. var _this = this;
  95466. if (configuration === this._imageProcessingConfiguration) {
  95467. return;
  95468. }
  95469. // Detaches observer.
  95470. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95471. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95472. }
  95473. // Pick the scene configuration if needed.
  95474. if (!configuration) {
  95475. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  95476. }
  95477. else {
  95478. this._imageProcessingConfiguration = configuration;
  95479. }
  95480. // Attaches observer.
  95481. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  95482. _this._computePrimaryColorFromPerceptualColor();
  95483. _this._markAllSubMeshesAsImageProcessingDirty();
  95484. });
  95485. };
  95486. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  95487. /**
  95488. * Gets the image processing configuration used either in this material.
  95489. */
  95490. get: function () {
  95491. return this._imageProcessingConfiguration;
  95492. },
  95493. /**
  95494. * Sets the Default image processing configuration used either in the this material.
  95495. *
  95496. * If sets to null, the scene one is in use.
  95497. */
  95498. set: function (value) {
  95499. this._attachImageProcessingConfiguration(value);
  95500. // Ensure the effect will be rebuilt.
  95501. this._markAllSubMeshesAsTexturesDirty();
  95502. },
  95503. enumerable: true,
  95504. configurable: true
  95505. });
  95506. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  95507. /**
  95508. * Gets wether the color curves effect is enabled.
  95509. */
  95510. get: function () {
  95511. return this.imageProcessingConfiguration.colorCurvesEnabled;
  95512. },
  95513. /**
  95514. * Sets wether the color curves effect is enabled.
  95515. */
  95516. set: function (value) {
  95517. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  95518. },
  95519. enumerable: true,
  95520. configurable: true
  95521. });
  95522. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  95523. /**
  95524. * Gets wether the color grading effect is enabled.
  95525. */
  95526. get: function () {
  95527. return this.imageProcessingConfiguration.colorGradingEnabled;
  95528. },
  95529. /**
  95530. * Gets wether the color grading effect is enabled.
  95531. */
  95532. set: function (value) {
  95533. this.imageProcessingConfiguration.colorGradingEnabled = value;
  95534. },
  95535. enumerable: true,
  95536. configurable: true
  95537. });
  95538. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  95539. /**
  95540. * Gets wether tonemapping is enabled or not.
  95541. */
  95542. get: function () {
  95543. return this._imageProcessingConfiguration.toneMappingEnabled;
  95544. },
  95545. /**
  95546. * Sets wether tonemapping is enabled or not
  95547. */
  95548. set: function (value) {
  95549. this._imageProcessingConfiguration.toneMappingEnabled = value;
  95550. },
  95551. enumerable: true,
  95552. configurable: true
  95553. });
  95554. ;
  95555. ;
  95556. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  95557. /**
  95558. * The camera exposure used on this material.
  95559. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95560. * This corresponds to a photographic exposure.
  95561. */
  95562. get: function () {
  95563. return this._imageProcessingConfiguration.exposure;
  95564. },
  95565. /**
  95566. * The camera exposure used on this material.
  95567. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95568. * This corresponds to a photographic exposure.
  95569. */
  95570. set: function (value) {
  95571. this._imageProcessingConfiguration.exposure = value;
  95572. },
  95573. enumerable: true,
  95574. configurable: true
  95575. });
  95576. ;
  95577. ;
  95578. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  95579. /**
  95580. * Gets The camera contrast used on this material.
  95581. */
  95582. get: function () {
  95583. return this._imageProcessingConfiguration.contrast;
  95584. },
  95585. /**
  95586. * Sets The camera contrast used on this material.
  95587. */
  95588. set: function (value) {
  95589. this._imageProcessingConfiguration.contrast = value;
  95590. },
  95591. enumerable: true,
  95592. configurable: true
  95593. });
  95594. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95595. /**
  95596. * Gets the Color Grading 2D Lookup Texture.
  95597. */
  95598. get: function () {
  95599. return this._imageProcessingConfiguration.colorGradingTexture;
  95600. },
  95601. /**
  95602. * Sets the Color Grading 2D Lookup Texture.
  95603. */
  95604. set: function (value) {
  95605. this.imageProcessingConfiguration.colorGradingTexture = value;
  95606. },
  95607. enumerable: true,
  95608. configurable: true
  95609. });
  95610. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95611. /**
  95612. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95613. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95614. * 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;
  95615. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95616. */
  95617. get: function () {
  95618. return this.imageProcessingConfiguration.colorCurves;
  95619. },
  95620. /**
  95621. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95622. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95623. * 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;
  95624. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95625. */
  95626. set: function (value) {
  95627. this.imageProcessingConfiguration.colorCurves = value;
  95628. },
  95629. enumerable: true,
  95630. configurable: true
  95631. });
  95632. /**
  95633. * The entire material has been created in order to prevent overdraw.
  95634. * @returns false
  95635. */
  95636. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95637. return true;
  95638. };
  95639. /**
  95640. * The entire material has been created in order to prevent overdraw.
  95641. * @returns true if blending is enable
  95642. */
  95643. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95644. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95645. };
  95646. /**
  95647. * Checks wether the material is ready to be rendered for a given mesh.
  95648. * @param mesh The mesh to render
  95649. * @param subMesh The submesh to check against
  95650. * @param useInstances Specify wether or not the material is used with instances
  95651. * @returns true if all the dependencies are ready (Textures, Effects...)
  95652. */
  95653. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95654. var _this = this;
  95655. if (useInstances === void 0) { useInstances = false; }
  95656. if (subMesh.effect && this.isFrozen) {
  95657. if (this._wasPreviouslyReady) {
  95658. return true;
  95659. }
  95660. }
  95661. if (!subMesh._materialDefines) {
  95662. subMesh._materialDefines = new BackgroundMaterialDefines();
  95663. }
  95664. var scene = this.getScene();
  95665. var defines = subMesh._materialDefines;
  95666. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95667. if (defines._renderId === scene.getRenderId()) {
  95668. return true;
  95669. }
  95670. }
  95671. var engine = scene.getEngine();
  95672. // Lights
  95673. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95674. defines._needNormals = true;
  95675. // Textures
  95676. if (defines._areTexturesDirty) {
  95677. defines._needUVs = false;
  95678. if (scene.texturesEnabled) {
  95679. if (scene.getEngine().getCaps().textureLOD) {
  95680. defines.TEXTURELODSUPPORT = true;
  95681. }
  95682. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95683. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95684. return false;
  95685. }
  95686. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95687. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95688. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95689. defines.OPACITYFRESNEL = this._opacityFresnel;
  95690. }
  95691. else {
  95692. defines.DIFFUSE = false;
  95693. defines.DIFFUSEHASALPHA = false;
  95694. defines.GAMMADIFFUSE = false;
  95695. defines.OPACITYFRESNEL = false;
  95696. }
  95697. var reflectionTexture = this._reflectionTexture;
  95698. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95699. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95700. return false;
  95701. }
  95702. defines.REFLECTION = true;
  95703. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95704. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95705. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95706. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95707. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95708. defines.REFLECTIONBGR = this.switchToBGR;
  95709. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95710. defines.INVERTCUBICMAP = true;
  95711. }
  95712. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95713. switch (reflectionTexture.coordinatesMode) {
  95714. case BABYLON.Texture.CUBIC_MODE:
  95715. case BABYLON.Texture.INVCUBIC_MODE:
  95716. defines.REFLECTIONMAP_CUBIC = true;
  95717. break;
  95718. case BABYLON.Texture.EXPLICIT_MODE:
  95719. defines.REFLECTIONMAP_EXPLICIT = true;
  95720. break;
  95721. case BABYLON.Texture.PLANAR_MODE:
  95722. defines.REFLECTIONMAP_PLANAR = true;
  95723. break;
  95724. case BABYLON.Texture.PROJECTION_MODE:
  95725. defines.REFLECTIONMAP_PROJECTION = true;
  95726. break;
  95727. case BABYLON.Texture.SKYBOX_MODE:
  95728. defines.REFLECTIONMAP_SKYBOX = true;
  95729. break;
  95730. case BABYLON.Texture.SPHERICAL_MODE:
  95731. defines.REFLECTIONMAP_SPHERICAL = true;
  95732. break;
  95733. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95734. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95735. break;
  95736. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95737. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95738. break;
  95739. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95740. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95741. break;
  95742. }
  95743. if (this.reflectionFresnel) {
  95744. defines.REFLECTIONFRESNEL = true;
  95745. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95746. this._reflectionControls.x = this.reflectionAmount;
  95747. this._reflectionControls.y = this.reflectionReflectance0;
  95748. this._reflectionControls.z = this.reflectionReflectance90;
  95749. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95750. }
  95751. else {
  95752. defines.REFLECTIONFRESNEL = false;
  95753. defines.REFLECTIONFALLOFF = false;
  95754. }
  95755. }
  95756. else {
  95757. defines.REFLECTION = false;
  95758. defines.REFLECTIONFRESNEL = false;
  95759. defines.REFLECTIONFALLOFF = false;
  95760. defines.REFLECTIONBLUR = false;
  95761. defines.REFLECTIONMAP_3D = false;
  95762. defines.REFLECTIONMAP_SPHERICAL = false;
  95763. defines.REFLECTIONMAP_PLANAR = false;
  95764. defines.REFLECTIONMAP_CUBIC = false;
  95765. defines.REFLECTIONMAP_PROJECTION = false;
  95766. defines.REFLECTIONMAP_SKYBOX = false;
  95767. defines.REFLECTIONMAP_EXPLICIT = false;
  95768. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95769. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95770. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95771. defines.INVERTCUBICMAP = false;
  95772. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95773. defines.LODINREFLECTIONALPHA = false;
  95774. defines.GAMMAREFLECTION = false;
  95775. }
  95776. }
  95777. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95778. defines.USERGBCOLOR = this._useRGBColor;
  95779. defines.NOISE = this._enableNoise;
  95780. }
  95781. if (defines._areLightsDirty) {
  95782. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95783. }
  95784. if (defines._areImageProcessingDirty) {
  95785. if (!this._imageProcessingConfiguration.isReady()) {
  95786. return false;
  95787. }
  95788. this._imageProcessingConfiguration.prepareDefines(defines);
  95789. }
  95790. // Misc.
  95791. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95792. // Values that need to be evaluated on every frame
  95793. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95794. // Attribs
  95795. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95796. if (mesh) {
  95797. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95798. mesh.createNormals(true);
  95799. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95800. }
  95801. }
  95802. }
  95803. // Get correct effect
  95804. if (defines.isDirty) {
  95805. defines.markAsProcessed();
  95806. scene.resetCachedMaterial();
  95807. // Fallbacks
  95808. var fallbacks = new BABYLON.EffectFallbacks();
  95809. if (defines.FOG) {
  95810. fallbacks.addFallback(0, "FOG");
  95811. }
  95812. if (defines.POINTSIZE) {
  95813. fallbacks.addFallback(1, "POINTSIZE");
  95814. }
  95815. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95816. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95817. fallbacks.addCPUSkinningFallback(0, mesh);
  95818. }
  95819. //Attributes
  95820. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95821. if (defines.NORMAL) {
  95822. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95823. }
  95824. if (defines.UV1) {
  95825. attribs.push(BABYLON.VertexBuffer.UVKind);
  95826. }
  95827. if (defines.UV2) {
  95828. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95829. }
  95830. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95831. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95832. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95833. "vFogInfos", "vFogColor", "pointSize",
  95834. "vClipPlane", "mBones",
  95835. "vPrimaryColor", "vPrimaryColorShadow",
  95836. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95837. "shadowLevel", "alpha",
  95838. "vBackgroundCenter", "vReflectionControl",
  95839. "vDiffuseInfos", "diffuseMatrix",
  95840. ];
  95841. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95842. var uniformBuffers = ["Material", "Scene"];
  95843. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95844. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95845. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95846. uniformsNames: uniforms,
  95847. uniformBuffersNames: uniformBuffers,
  95848. samplers: samplers,
  95849. defines: defines,
  95850. maxSimultaneousLights: this._maxSimultaneousLights
  95851. });
  95852. var onCompiled = function (effect) {
  95853. if (_this.onCompiled) {
  95854. _this.onCompiled(effect);
  95855. }
  95856. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95857. };
  95858. var join = defines.toString();
  95859. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95860. attributes: attribs,
  95861. uniformsNames: uniforms,
  95862. uniformBuffersNames: uniformBuffers,
  95863. samplers: samplers,
  95864. defines: join,
  95865. fallbacks: fallbacks,
  95866. onCompiled: onCompiled,
  95867. onError: this.onError,
  95868. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95869. }, engine), defines);
  95870. this.buildUniformLayout();
  95871. }
  95872. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95873. return false;
  95874. }
  95875. defines._renderId = scene.getRenderId();
  95876. this._wasPreviouslyReady = true;
  95877. return true;
  95878. };
  95879. /**
  95880. * Compute the primary color according to the chosen perceptual color.
  95881. */
  95882. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  95883. if (!this.__perceptualColor) {
  95884. return;
  95885. }
  95886. this._primaryColor.copyFrom(this.__perceptualColor);
  95887. // Revert gamma space.
  95888. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  95889. // Revert image processing configuration.
  95890. if (this._imageProcessingConfiguration) {
  95891. // Revert Exposure.
  95892. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  95893. }
  95894. this._computePrimaryColors();
  95895. };
  95896. /**
  95897. * Compute the highlights and shadow colors according to their chosen levels.
  95898. */
  95899. BackgroundMaterial.prototype._computePrimaryColors = function () {
  95900. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  95901. return;
  95902. }
  95903. // Find the highlight color based on the configuration.
  95904. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  95905. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  95906. // Find the shadow color based on the configuration.
  95907. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  95908. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  95909. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  95910. };
  95911. /**
  95912. * Build the uniform buffer used in the material.
  95913. */
  95914. BackgroundMaterial.prototype.buildUniformLayout = function () {
  95915. // Order is important !
  95916. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  95917. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  95918. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  95919. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  95920. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  95921. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  95922. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  95923. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  95924. this._uniformBuffer.addUniform("pointSize", 1);
  95925. this._uniformBuffer.addUniform("shadowLevel", 1);
  95926. this._uniformBuffer.addUniform("alpha", 1);
  95927. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  95928. this._uniformBuffer.addUniform("vReflectionControl", 4);
  95929. this._uniformBuffer.create();
  95930. };
  95931. /**
  95932. * Unbind the material.
  95933. */
  95934. BackgroundMaterial.prototype.unbind = function () {
  95935. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  95936. this._uniformBuffer.setTexture("diffuseSampler", null);
  95937. }
  95938. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  95939. this._uniformBuffer.setTexture("reflectionSampler", null);
  95940. }
  95941. _super.prototype.unbind.call(this);
  95942. };
  95943. /**
  95944. * Bind only the world matrix to the material.
  95945. * @param world The world matrix to bind.
  95946. */
  95947. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  95948. this._activeEffect.setMatrix("world", world);
  95949. };
  95950. /**
  95951. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  95952. * @param world The world matrix to bind.
  95953. * @param subMesh The submesh to bind for.
  95954. */
  95955. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  95956. var scene = this.getScene();
  95957. var defines = subMesh._materialDefines;
  95958. if (!defines) {
  95959. return;
  95960. }
  95961. var effect = subMesh.effect;
  95962. if (!effect) {
  95963. return;
  95964. }
  95965. this._activeEffect = effect;
  95966. // Matrices
  95967. this.bindOnlyWorldMatrix(world);
  95968. // Bones
  95969. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95970. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95971. if (mustRebind) {
  95972. this._uniformBuffer.bindToEffect(effect, "Material");
  95973. this.bindViewProjection(effect);
  95974. var reflectionTexture = this._reflectionTexture;
  95975. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95976. // Texture uniforms
  95977. if (scene.texturesEnabled) {
  95978. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95979. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95980. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95981. }
  95982. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95983. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95984. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95985. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95986. }
  95987. }
  95988. if (this.shadowLevel > 0) {
  95989. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95990. }
  95991. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95992. // Point size
  95993. if (this.pointsCloud) {
  95994. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95995. }
  95996. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  95997. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  95998. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  95999. }
  96000. else {
  96001. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96002. }
  96003. }
  96004. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96005. // Textures
  96006. if (scene.texturesEnabled) {
  96007. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96008. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96009. }
  96010. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96011. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96012. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96013. }
  96014. else if (!defines.REFLECTIONBLUR) {
  96015. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96016. }
  96017. else {
  96018. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96019. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96020. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96021. }
  96022. if (defines.REFLECTIONFRESNEL) {
  96023. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96024. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96025. }
  96026. }
  96027. }
  96028. // Clip plane
  96029. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96030. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96031. }
  96032. if (mustRebind || !this.isFrozen) {
  96033. if (scene.lightsEnabled) {
  96034. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96035. }
  96036. // View
  96037. this.bindView(effect);
  96038. // Fog
  96039. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96040. // image processing
  96041. this._imageProcessingConfiguration.bind(this._activeEffect);
  96042. }
  96043. this._uniformBuffer.update();
  96044. this._afterBind(mesh);
  96045. };
  96046. /**
  96047. * Dispose the material.
  96048. * @param forceDisposeEffect Force disposal of the associated effect.
  96049. * @param forceDisposeTextures Force disposal of the associated textures.
  96050. */
  96051. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96052. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96053. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96054. if (forceDisposeTextures) {
  96055. if (this.diffuseTexture) {
  96056. this.diffuseTexture.dispose();
  96057. }
  96058. if (this.reflectionTexture) {
  96059. this.reflectionTexture.dispose();
  96060. }
  96061. }
  96062. this._renderTargets.dispose();
  96063. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96064. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96065. }
  96066. _super.prototype.dispose.call(this, forceDisposeEffect);
  96067. };
  96068. /**
  96069. * Clones the material.
  96070. * @param name The cloned name.
  96071. * @returns The cloned material.
  96072. */
  96073. BackgroundMaterial.prototype.clone = function (name) {
  96074. var _this = this;
  96075. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96076. };
  96077. /**
  96078. * Serializes the current material to its JSON representation.
  96079. * @returns The JSON representation.
  96080. */
  96081. BackgroundMaterial.prototype.serialize = function () {
  96082. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96083. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96084. return serializationObject;
  96085. };
  96086. /**
  96087. * Gets the class name of the material
  96088. * @returns "BackgroundMaterial"
  96089. */
  96090. BackgroundMaterial.prototype.getClassName = function () {
  96091. return "BackgroundMaterial";
  96092. };
  96093. /**
  96094. * Parse a JSON input to create back a background material.
  96095. * @param source The JSON data to parse
  96096. * @param scene The scene to create the parsed material in
  96097. * @param rootUrl The root url of the assets the material depends upon
  96098. * @returns the instantiated BackgroundMaterial.
  96099. */
  96100. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96101. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96102. };
  96103. /**
  96104. * Standard reflectance value at parallel view angle.
  96105. */
  96106. BackgroundMaterial.StandardReflectance0 = 0.05;
  96107. /**
  96108. * Standard reflectance value at grazing angle.
  96109. */
  96110. BackgroundMaterial.StandardReflectance90 = 0.5;
  96111. __decorate([
  96112. BABYLON.serializeAsColor3()
  96113. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96114. __decorate([
  96115. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96116. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96117. __decorate([
  96118. BABYLON.serializeAsColor3()
  96119. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96120. __decorate([
  96121. BABYLON.serialize()
  96122. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96123. __decorate([
  96124. BABYLON.serialize()
  96125. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96126. __decorate([
  96127. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96128. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96129. __decorate([
  96130. BABYLON.serializeAsTexture()
  96131. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96132. __decorate([
  96133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96134. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96135. __decorate([
  96136. BABYLON.serialize()
  96137. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96138. __decorate([
  96139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96140. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96141. __decorate([
  96142. BABYLON.serializeAsTexture()
  96143. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96144. __decorate([
  96145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96146. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96147. __decorate([
  96148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96149. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96150. __decorate([
  96151. BABYLON.serialize()
  96152. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96153. __decorate([
  96154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96155. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96156. __decorate([
  96157. BABYLON.serializeAsVector3()
  96158. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96159. __decorate([
  96160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96161. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96162. __decorate([
  96163. BABYLON.serialize()
  96164. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96165. __decorate([
  96166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96167. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96168. __decorate([
  96169. BABYLON.serialize()
  96170. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96171. __decorate([
  96172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96173. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96174. __decorate([
  96175. BABYLON.serialize()
  96176. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96177. __decorate([
  96178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96179. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96180. __decorate([
  96181. BABYLON.serialize()
  96182. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96183. __decorate([
  96184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96185. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96186. __decorate([
  96187. BABYLON.serialize()
  96188. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96189. __decorate([
  96190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96191. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96192. __decorate([
  96193. BABYLON.serialize()
  96194. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96195. __decorate([
  96196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96197. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96198. __decorate([
  96199. BABYLON.serialize()
  96200. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96201. __decorate([
  96202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96203. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96204. __decorate([
  96205. BABYLON.serialize()
  96206. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96207. __decorate([
  96208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96209. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96210. __decorate([
  96211. BABYLON.serialize()
  96212. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96213. __decorate([
  96214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96215. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96216. __decorate([
  96217. BABYLON.serializeAsImageProcessingConfiguration()
  96218. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96219. return BackgroundMaterial;
  96220. }(BABYLON.PushMaterial));
  96221. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96222. })(BABYLON || (BABYLON = {}));
  96223. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96224. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96225. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96226. s = arguments[i];
  96227. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96228. t[p] = s[p];
  96229. }
  96230. return t;
  96231. };
  96232. var BABYLON;
  96233. (function (BABYLON) {
  96234. /**
  96235. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96236. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96237. * It also helps with the default setup of your imageProcessing configuration.
  96238. */
  96239. var EnvironmentHelper = /** @class */ (function () {
  96240. /**
  96241. * constructor
  96242. * @param options
  96243. * @param scene The scene to add the material to
  96244. */
  96245. function EnvironmentHelper(options, scene) {
  96246. var _this = this;
  96247. this._errorHandler = function (message, exception) {
  96248. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96249. };
  96250. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96251. this._scene = scene;
  96252. this.onErrorObservable = new BABYLON.Observable();
  96253. this._setupBackground();
  96254. this._setupImageProcessing();
  96255. }
  96256. /**
  96257. * Creates the default options for the helper.
  96258. */
  96259. EnvironmentHelper._getDefaultOptions = function () {
  96260. return {
  96261. createGround: true,
  96262. groundSize: 15,
  96263. groundTexture: this._groundTextureCDNUrl,
  96264. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96265. groundOpacity: 0.9,
  96266. enableGroundShadow: true,
  96267. groundShadowLevel: 0.5,
  96268. enableGroundMirror: false,
  96269. groundMirrorSizeRatio: 0.3,
  96270. groundMirrorBlurKernel: 64,
  96271. groundMirrorAmount: 1,
  96272. groundMirrorFresnelWeight: 1,
  96273. groundMirrorFallOffDistance: 0,
  96274. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96275. groundYBias: 0.00001,
  96276. createSkybox: true,
  96277. skyboxSize: 20,
  96278. skyboxTexture: this._skyboxTextureCDNUrl,
  96279. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96280. backgroundYRotation: 0,
  96281. sizeAuto: true,
  96282. rootPosition: BABYLON.Vector3.Zero(),
  96283. setupImageProcessing: true,
  96284. environmentTexture: this._environmentTextureCDNUrl,
  96285. cameraExposure: 0.8,
  96286. cameraContrast: 1.2,
  96287. toneMappingEnabled: true,
  96288. };
  96289. };
  96290. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96291. /**
  96292. * Gets the root mesh created by the helper.
  96293. */
  96294. get: function () {
  96295. return this._rootMesh;
  96296. },
  96297. enumerable: true,
  96298. configurable: true
  96299. });
  96300. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96301. /**
  96302. * Gets the skybox created by the helper.
  96303. */
  96304. get: function () {
  96305. return this._skybox;
  96306. },
  96307. enumerable: true,
  96308. configurable: true
  96309. });
  96310. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96311. /**
  96312. * Gets the skybox texture created by the helper.
  96313. */
  96314. get: function () {
  96315. return this._skyboxTexture;
  96316. },
  96317. enumerable: true,
  96318. configurable: true
  96319. });
  96320. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96321. /**
  96322. * Gets the skybox material created by the helper.
  96323. */
  96324. get: function () {
  96325. return this._skyboxMaterial;
  96326. },
  96327. enumerable: true,
  96328. configurable: true
  96329. });
  96330. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96331. /**
  96332. * Gets the ground mesh created by the helper.
  96333. */
  96334. get: function () {
  96335. return this._ground;
  96336. },
  96337. enumerable: true,
  96338. configurable: true
  96339. });
  96340. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96341. /**
  96342. * Gets the ground texture created by the helper.
  96343. */
  96344. get: function () {
  96345. return this._groundTexture;
  96346. },
  96347. enumerable: true,
  96348. configurable: true
  96349. });
  96350. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96351. /**
  96352. * Gets the ground mirror created by the helper.
  96353. */
  96354. get: function () {
  96355. return this._groundMirror;
  96356. },
  96357. enumerable: true,
  96358. configurable: true
  96359. });
  96360. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96361. /**
  96362. * Gets the ground mirror render list to helps pushing the meshes
  96363. * you wish in the ground reflection.
  96364. */
  96365. get: function () {
  96366. if (this._groundMirror) {
  96367. return this._groundMirror.renderList;
  96368. }
  96369. return null;
  96370. },
  96371. enumerable: true,
  96372. configurable: true
  96373. });
  96374. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  96375. /**
  96376. * Gets the ground material created by the helper.
  96377. */
  96378. get: function () {
  96379. return this._groundMaterial;
  96380. },
  96381. enumerable: true,
  96382. configurable: true
  96383. });
  96384. /**
  96385. * Updates the background according to the new options
  96386. * @param options
  96387. */
  96388. EnvironmentHelper.prototype.updateOptions = function (options) {
  96389. var newOptions = __assign({}, this._options, options);
  96390. if (this._ground && !newOptions.createGround) {
  96391. this._ground.dispose();
  96392. this._ground = null;
  96393. }
  96394. if (this._groundMaterial && !newOptions.createGround) {
  96395. this._groundMaterial.dispose();
  96396. this._groundMaterial = null;
  96397. }
  96398. if (this._groundTexture) {
  96399. if (this._options.groundTexture != newOptions.groundTexture) {
  96400. this._groundTexture.dispose();
  96401. this._groundTexture = null;
  96402. }
  96403. }
  96404. if (this._skybox && !newOptions.createSkybox) {
  96405. this._skybox.dispose();
  96406. this._skybox = null;
  96407. }
  96408. if (this._skyboxMaterial && !newOptions.createSkybox) {
  96409. this._skyboxMaterial.dispose();
  96410. this._skyboxMaterial = null;
  96411. }
  96412. if (this._skyboxTexture) {
  96413. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  96414. this._skyboxTexture.dispose();
  96415. this._skyboxTexture = null;
  96416. }
  96417. }
  96418. if (this._groundMirror && !newOptions.enableGroundMirror) {
  96419. this._groundMirror.dispose();
  96420. this._groundMirror = null;
  96421. }
  96422. if (this._scene.environmentTexture) {
  96423. if (this._options.environmentTexture != newOptions.environmentTexture) {
  96424. this._scene.environmentTexture.dispose();
  96425. }
  96426. }
  96427. this._options = newOptions;
  96428. this._setupBackground();
  96429. this._setupImageProcessing();
  96430. };
  96431. /**
  96432. * Sets the primary color of all the available elements.
  96433. * @param color the main color to affect to the ground and the background
  96434. */
  96435. EnvironmentHelper.prototype.setMainColor = function (color) {
  96436. if (this.groundMaterial) {
  96437. this.groundMaterial.primaryColor = color;
  96438. }
  96439. if (this.skyboxMaterial) {
  96440. this.skyboxMaterial.primaryColor = color;
  96441. }
  96442. if (this.groundMirror) {
  96443. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  96444. }
  96445. };
  96446. /**
  96447. * Setup the image processing according to the specified options.
  96448. */
  96449. EnvironmentHelper.prototype._setupImageProcessing = function () {
  96450. if (this._options.setupImageProcessing) {
  96451. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  96452. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  96453. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  96454. this._setupEnvironmentTexture();
  96455. }
  96456. };
  96457. /**
  96458. * Setup the environment texture according to the specified options.
  96459. */
  96460. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  96461. if (this._scene.environmentTexture) {
  96462. return;
  96463. }
  96464. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  96465. this._scene.environmentTexture = this._options.environmentTexture;
  96466. return;
  96467. }
  96468. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  96469. this._scene.environmentTexture = environmentTexture;
  96470. };
  96471. /**
  96472. * Setup the background according to the specified options.
  96473. */
  96474. EnvironmentHelper.prototype._setupBackground = function () {
  96475. if (!this._rootMesh) {
  96476. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  96477. }
  96478. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  96479. var sceneSize = this._getSceneSize();
  96480. if (this._options.createGround) {
  96481. this._setupGround(sceneSize);
  96482. this._setupGroundMaterial();
  96483. this._setupGroundDiffuseTexture();
  96484. if (this._options.enableGroundMirror) {
  96485. this._setupGroundMirrorTexture(sceneSize);
  96486. }
  96487. this._setupMirrorInGroundMaterial();
  96488. }
  96489. if (this._options.createSkybox) {
  96490. this._setupSkybox(sceneSize);
  96491. this._setupSkyboxMaterial();
  96492. this._setupSkyboxReflectionTexture();
  96493. }
  96494. this._rootMesh.position.x = sceneSize.rootPosition.x;
  96495. this._rootMesh.position.z = sceneSize.rootPosition.z;
  96496. this._rootMesh.position.y = sceneSize.rootPosition.y;
  96497. };
  96498. /**
  96499. * Get the scene sizes according to the setup.
  96500. */
  96501. EnvironmentHelper.prototype._getSceneSize = function () {
  96502. var _this = this;
  96503. var groundSize = this._options.groundSize;
  96504. var skyboxSize = this._options.skyboxSize;
  96505. var rootPosition = this._options.rootPosition;
  96506. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  96507. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96508. }
  96509. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  96510. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  96511. });
  96512. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  96513. if (this._options.sizeAuto) {
  96514. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  96515. this._scene.activeCamera.upperRadiusLimit) {
  96516. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  96517. skyboxSize = groundSize;
  96518. }
  96519. var sceneDiagonalLenght = sceneDiagonal.length();
  96520. if (sceneDiagonalLenght > groundSize) {
  96521. groundSize = sceneDiagonalLenght * 2;
  96522. skyboxSize = groundSize;
  96523. }
  96524. // 10 % bigger.
  96525. groundSize *= 1.1;
  96526. skyboxSize *= 1.5;
  96527. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  96528. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  96529. }
  96530. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96531. };
  96532. /**
  96533. * Setup the ground according to the specified options.
  96534. */
  96535. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  96536. var _this = this;
  96537. if (!this._ground) {
  96538. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  96539. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  96540. this._ground.parent = this._rootMesh;
  96541. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96542. }
  96543. this._ground.receiveShadows = this._options.enableGroundShadow;
  96544. };
  96545. /**
  96546. * Setup the ground material according to the specified options.
  96547. */
  96548. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96549. if (!this._groundMaterial) {
  96550. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96551. }
  96552. this._groundMaterial.alpha = this._options.groundOpacity;
  96553. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96554. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96555. this._groundMaterial.primaryColor = this._options.groundColor;
  96556. this._groundMaterial.useRGBColor = false;
  96557. this._groundMaterial.enableNoise = true;
  96558. if (this._ground) {
  96559. this._ground.material = this._groundMaterial;
  96560. }
  96561. };
  96562. /**
  96563. * Setup the ground diffuse texture according to the specified options.
  96564. */
  96565. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96566. if (!this._groundMaterial) {
  96567. return;
  96568. }
  96569. if (this._groundTexture) {
  96570. return;
  96571. }
  96572. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96573. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96574. return;
  96575. }
  96576. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96577. diffuseTexture.gammaSpace = false;
  96578. diffuseTexture.hasAlpha = true;
  96579. this._groundMaterial.diffuseTexture = diffuseTexture;
  96580. };
  96581. /**
  96582. * Setup the ground mirror texture according to the specified options.
  96583. */
  96584. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96585. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96586. if (!this._groundMirror) {
  96587. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96588. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96589. this._groundMirror.anisotropicFilteringLevel = 1;
  96590. this._groundMirror.wrapU = wrapping;
  96591. this._groundMirror.wrapV = wrapping;
  96592. this._groundMirror.gammaSpace = false;
  96593. if (this._groundMirror.renderList) {
  96594. for (var i = 0; i < this._scene.meshes.length; i++) {
  96595. var mesh = this._scene.meshes[i];
  96596. if (mesh !== this._ground &&
  96597. mesh !== this._skybox &&
  96598. mesh !== this._rootMesh) {
  96599. this._groundMirror.renderList.push(mesh);
  96600. }
  96601. }
  96602. }
  96603. }
  96604. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96605. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96606. };
  96607. /**
  96608. * Setup the ground to receive the mirror texture.
  96609. */
  96610. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96611. if (this._groundMaterial) {
  96612. this._groundMaterial.reflectionTexture = this._groundMirror;
  96613. this._groundMaterial.reflectionFresnel = true;
  96614. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96615. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96616. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96617. }
  96618. };
  96619. /**
  96620. * Setup the skybox according to the specified options.
  96621. */
  96622. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96623. var _this = this;
  96624. if (!this._skybox) {
  96625. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96626. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96627. }
  96628. this._skybox.parent = this._rootMesh;
  96629. };
  96630. /**
  96631. * Setup the skybox material according to the specified options.
  96632. */
  96633. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96634. if (!this._skybox) {
  96635. return;
  96636. }
  96637. if (!this._skyboxMaterial) {
  96638. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96639. }
  96640. this._skyboxMaterial.useRGBColor = false;
  96641. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96642. this._skyboxMaterial.enableNoise = true;
  96643. this._skybox.material = this._skyboxMaterial;
  96644. };
  96645. /**
  96646. * Setup the skybox reflection texture according to the specified options.
  96647. */
  96648. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96649. if (!this._skyboxMaterial) {
  96650. return;
  96651. }
  96652. if (this._skyboxTexture) {
  96653. return;
  96654. }
  96655. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96656. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  96657. return;
  96658. }
  96659. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96660. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96661. this._skyboxTexture.gammaSpace = false;
  96662. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96663. };
  96664. /**
  96665. * Dispose all the elements created by the Helper.
  96666. */
  96667. EnvironmentHelper.prototype.dispose = function () {
  96668. if (this._groundMaterial) {
  96669. this._groundMaterial.dispose(true, true);
  96670. }
  96671. if (this._skyboxMaterial) {
  96672. this._skyboxMaterial.dispose(true, true);
  96673. }
  96674. this._rootMesh.dispose(false);
  96675. };
  96676. /**
  96677. * Default ground texture URL.
  96678. */
  96679. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96680. /**
  96681. * Default skybox texture URL.
  96682. */
  96683. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96684. /**
  96685. * Default environment texture URL.
  96686. */
  96687. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96688. return EnvironmentHelper;
  96689. }());
  96690. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96691. })(BABYLON || (BABYLON = {}));
  96692. //# sourceMappingURL=babylon.environmentHelper.js.map
  96693. var BABYLON;
  96694. (function (BABYLON) {
  96695. /**
  96696. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96697. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96698. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96699. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96700. */
  96701. var VideoDome = /** @class */ (function (_super) {
  96702. __extends(VideoDome, _super);
  96703. /**
  96704. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96705. * @param name Element's name, child elements will append suffixes for their own names.
  96706. * @param urlsOrVideo
  96707. * @param options An object containing optional or exposed sub element properties:
  96708. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96709. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96710. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96711. * @param options **loop=true** Automatically loop video on end.
  96712. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96713. */
  96714. function VideoDome(name, urlsOrVideo, options, scene) {
  96715. var _this = _super.call(this, name, scene) || this;
  96716. // set defaults and manage values
  96717. name = name || "videoDome";
  96718. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96719. options.clickToPlay = Boolean(options.clickToPlay);
  96720. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96721. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96722. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96723. // create
  96724. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96725. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96726. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96727. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96728. flat: false,
  96729. radius: options.size,
  96730. subdivisions: options.resolution,
  96731. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96732. }, scene);
  96733. // configure material
  96734. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96735. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96736. material.reflectionTexture = _this._videoTexture;
  96737. material.useEquirectangularFOV = true;
  96738. material.fovMultiplier = 1.0;
  96739. // configure mesh
  96740. _this._mesh.material = material;
  96741. _this._mesh.parent = _this;
  96742. // optional configuration
  96743. if (options.clickToPlay) {
  96744. scene.onPointerUp = function () {
  96745. _this._videoTexture.video.play();
  96746. };
  96747. }
  96748. return _this;
  96749. }
  96750. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96751. /**
  96752. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96753. * Also see the options.resolution property.
  96754. */
  96755. get: function () {
  96756. return this._material.fovMultiplier;
  96757. },
  96758. set: function (value) {
  96759. this._material.fovMultiplier = value;
  96760. },
  96761. enumerable: true,
  96762. configurable: true
  96763. });
  96764. /**
  96765. * Releases resources associated with this node.
  96766. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96767. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96768. */
  96769. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96770. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96771. this._videoTexture.dispose();
  96772. this._mesh.dispose();
  96773. this._material.dispose();
  96774. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96775. };
  96776. return VideoDome;
  96777. }(BABYLON.Node));
  96778. BABYLON.VideoDome = VideoDome;
  96779. })(BABYLON || (BABYLON = {}));
  96780. //# sourceMappingURL=babylon.videoDome.js.map
  96781. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  96782. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};